qrcode-react icon indicating copy to clipboard operation
qrcode-react copied to clipboard

Jest Snapshot Test Failure: Cannot read property 'getContext' of null

Open joncursi opened this issue 7 years ago • 5 comments

// 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 />)

joncursi avatar Dec 20 '17 18:12 joncursi

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.

danielcooperxyz avatar Jun 15 '18 07:06 danielcooperxyz

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 avatar Jun 15 '18 08:06 danielcooperxyz

@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.

codeepic avatar May 10 '19 14:05 codeepic

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

zhuangya avatar Aug 13 '19 12:08 zhuangya

@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.

Did you get your issue resolved ?? If yes , please help me. I am getting the same error working on React testing using Jest.

PatilAkshay-1 avatar May 11 '21 11:05 PatilAkshay-1