qrcode-react
qrcode-react copied to clipboard
Jest Snapshot Test Failure: Cannot read property 'getContext' of null
// tests.js
import * as React from 'react';
import renderer from 'react-test-renderer';
import QrCode from '.';
it('renders correctly', () => {
const tree = renderer
.create(<QrCode />)
.toJSON();
expect(tree).toMatchSnapshot();
});
Error:
TypeError: Cannot read property 'getContext' of null
6 | it('renders correctly', () => {
7 | const tree = renderer
> 8 | .create(<QrCode />)
I get a similar issue when attempting to render my app.
TypeError: Cannot read property 'webkitBackingStorePixelRatio' of null
15 | };
16 |
> 17 | ReactDOM.render(
| ^
18 | <Provider store={mockStore(state)}>
19 | <App />
20 | </Provider>,
at getBackingStorePixelRatio (node_modules/qrcode-react/dist/index.js:17:15)
at QRCode.update (node_modules/qrcode-react/dist/index.js:90:58)
at QRCode.componentDidMount (node_modules/qrcode-react/dist/index.js:51:18)
at commitLifeCycles (node_modules/react-dom/cjs/react-dom.development.js:14248:10)
I think this is related to a need for mocking the canvas, as Jest uses JSDom to "render" the components.
Doing a little more research I found that jsdom does have support for canvas via an external package.
Installing canvas or canvas-prebuilt as a dependency allowed it to work for me.
@danielcooperxyz I added canvas-prebuilt
package to devDependencies and moved it to dependencies but in both cases I am still getting an error TypeError: Cannot read property 'backingStorePixelRatio' of null
when running Jest tests.
Using https://github.com/hustcc/jest-canvas-mock. If you are using Create React App just add import 'jest-canvas-mock' in your setupTests.js
credit: https://stackoverflow.com/a/53478780/553523
@danielcooperxyz I added
canvas-prebuilt
package to devDependencies and moved it to dependencies but in both cases I am still getting an errorTypeError: Cannot read property 'backingStorePixelRatio' of null
when running Jest tests.
Did you get your issue resolved ?? If yes , please help me. I am getting the same error working on React testing using Jest.