Jest Test Fails: Typeerror: Window. matchMedia Is Not a Function
This Is My First Front-End Testing Experience. in This Project, I'm Using Jest Snapshot Testing and Got an Error Typeerror: Window. matchMedia Is Not a...
This is my first front-end testing experience. In this project, I'm using Jest snapshot testing and got an error TypeError: window.matchMedia is not a function inside my component.
I go through Jest documentation, I found the "Manual mocks" section, but I have not any idea about how to do that yet.
20 Answers
The Jest documentation now has an "official" workaround:
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // Deprecated
removeListener: jest.fn(), // Deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
I've been using this technique to solve a bunch of mocking problems.
describe("Test", () => {
beforeAll(() => {
Object.defineProperty(window, "matchMedia", {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // Deprecated
removeListener: jest.fn(), // Deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
}))
});
});
});
Or, if you want to mock it all the time, you could put inside your mocks file called from your package.json:
"setupFilesAfterEnv": "<rootDir>/src/tests/mocks.js",.
Reference: setupTestFrameworkScriptFile
I put a matchMedia stub in my Jest test file (above the tests), which allows the tests to pass:
window.matchMedia = window.matchMedia || function() {
return {
matches: false,
addListener: function() {},
removeListener: function() {}
};
};
Must Read
JESTS OFFICIAL WORKAROUND
is to create a mock file, called matchMedia.js and add the following code:
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation((query) => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // Deprecated
removeListener: jest.fn(), // Deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
Then, inside your test file, import your mock import './matchMedia';
and as long as you import it in every use case, it should solve your problem.