TypeError: win.matchMedia is not a function during unit test
See original GitHub issueDescription
When I render a ChakraProvider inside a unit test (for example, to test a component which uses the useToast hook) an error is thrown by the color mode query function TypeError: win.matchMedia is not a function
.
Link to Reproduction
https://github.com/stefee/chakra-repro-6036
Steps to reproduce
git clone git@github.com:stefee/chakra-repro-6036.git
cd chakra-repro-6036
npm install
npm test
Chakra UI Version
2.0.0
Browser
Jest
Operating System
- macOS
- Windows
- Linux
Additional Information
No response
Issue Analytics
- State:
- Created a year ago
- Reactions:1
- Comments:5 (4 by maintainers)
Top Results From Across the Web
Jest test fails : TypeError: window.matchMedia is not a function
In this project, I'm using Jest snapshot testing and got an error TypeError: window.matchMedia is not a function inside my component.
Read more >4.0.0-rc.1 TypeError: window.matchMedia is not a function in ...
You can fix this by mocking the window.matchMedia method in the setupTests.js file or before your tests. Here's the mock I use: Object....
Read more >Jest test fails : TypeError: window.matchMedia is not a function
When use jest to test e.g. with Antd library, you probably will meet this error. Jest test fails : TypeError: window.matchMedia is not...
Read more >Manual Mocks - Jest
Jest returns TypeError: window.matchMedia is not a function and doesn't properly execute the test. In this case, mocking matchMedia in the ...
Read more >Jest test fails : TypeError: window.matchMedia is not a function ...
If the component you are testing includes window.matchMedia() or imports another component (ie. a CSS media query hook uses useMedia() ) and you...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Hey @stefee, check out my PR to your sample repo: https://github.com/stefee/chakra-repro-6036/pull/1
For future reference in case the Repo will be deleted / the PR is gone:
jest.setup.js
(or .ts)jest.setup.js/ts
file in yourjest.config.js/ts
Find some more info in the jest official documentation: https://jestjs.io/docs/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom
This has little to do with chakra, but the fact that JSDOM (the DOM implementation used by Jest) has not implemented
matchMedia
, so you have to mock it.This issue was fully resolved in the latest release of Chakra UI (2.0.2) so the manual mock is no longer required.