Sometimes, we want to fix the ‘TypeError: window.matchMedia is not a function’ error in Jest tests.
In this article, we’ll look at how to fix the ‘TypeError: window.matchMedia is not a function’ error in Jest tests.
How to fix the ‘TypeError: window.matchMedia is not a function’ error in Jest tests?
To fix the ‘TypeError: window.matchMedia is not a function’ error in Jest tests, we can add a mocked version of the window.matchMedia
method.
To do this, we write
describe("Test", () => {
beforeAll(() => {
Object.defineProperty(window, "matchMedia", {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(),
removeListener: jest.fn(),
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
}))
});
});
});
to call Object.defineProperty
to add the matchMedia
property to window
.
We set it to a mocked function that we get by calling jest.fn
.
And we call mockImplementation
with a function that returns a bunch of properties that are returned by matchMedia
like matches
, media
, onChange
, etc.
We mock the methods with jest.fn
and set the rest to different fake values.
We put the mock code in the beforeAll
callback so it’s called before all tests.
Conclusion
To fix the ‘TypeError: window.matchMedia is not a function’ error in Jest tests, we can add a mocked version of the window.matchMedia
method.