react-slick: Testing with Jest causes error

I’m using creact-react-app which uses jest for testing. During default test which is provided by create-react-app it throws error about matchMedia. Because jest is getting more popular for react testing it would be convenient to prevent this by default.

matchMedia not present, legacy browsers require a polyfill

  at Object.MediaQueryDispatch (node_modules/enquire.js/dist/enquire.js:226:19)
  at node_modules/enquire.js/dist/enquire.js:291:9
  at i (node_modules/enquire.js/dist/enquire.js:11:20)
  at Object.<anonymous> (node_modules/enquire.js/dist/enquire.js:21:2)
  at Object.<anonymous> (node_modules/react-responsive-mixin/index.js:2:28)
  at Object.<anonymous> (node_modules/react-slick/lib/slider.js:19:29)
  at Object.<anonymous> (node_modules/react-slick/lib/index.js:3:18)
  at Object.<anonymous> (src/components/Testimonials.jsx:3:45)
  at Object.<anonymous> (src/pages/Index.jsx:7:47)
  at Object.<anonymous> (src/App.jsx:8:40)
  at Object.<anonymous> (src/App.test.jsx:3:38)
  at process._tickCallback (internal/process/next_tick.js:103:7)

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 8
  • Comments: 17 (3 by maintainers)

Most upvoted comments

Add matchMedia to setup.js

window.matchMedia = window.matchMedia || (() => { return { matches: false, addListener: () => {}, removeListener: () => {}, }; });

@romkacrv , I added matchMedia.js to __mocks__ folder, which contained inside it:

// __mocks__/matchMedia.js
'use strict';

Object.defineProperty(window, 'matchMedia', {
	value: () => ({
		matches: false,
		addListener: () => {},
		removeListener: () => {}
	})
});

Object.defineProperty(window, 'getComputedStyle', {
	value: () => ({
		getPropertyValue: () => {}
	})
});

module.exports = window;

then imported this in setup.js import matchMedia from '../__mocks__/matchMedia';

Boom! πŸ˜ƒ

hello, not working for me, any suggestions ? it’s appear using react-snapshot plugin

Thanks funciono correctamente: window.matchMedia = window.matchMedia || (() => { return { matches: false, addListener: () => {}, removeListener: () => {}, } }) y en jest.conf

const config = { rootDir: β€˜β€¦/’, preset: β€˜@redwoodjs/testing/config/jest/web’, resolver: path.resolve(__dirname, β€˜./web-custom-resolver.js’), transformIgnorePatterns: [ // Update from this πŸ‘ˆ // β€œ[/\\]node_modules[/\\].+\.(js|jsx|mjs|cjs|ts|tsx)$”, [/\\\\]node_modules[/\\\\](?!${esModules}).+\\.(js|jsx|mjs|cjs|ts|tsx)$, // To this πŸ‘ˆ β€˜^.+\.module\.(css|sass|scss)$’, ], setupFilesAfterEnv: [β€˜web/src/setupTest.js’], }

module.exports = config

@arakno worked for me. But I imported the file in my .test.js file. Thanks for the help.

@arakno That worked for me. Thanks a lot for this