I am getting the following error when testing using window.matchMedia
. This runs fine in production and locally, it is only an issue during testing.
I am using React 18 with vite.
TypeError: Cannot read properties of undefined (reading 'matches')
It is suggested in the jest docs to add the following to my setupTests.js
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: vi.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: vi.fn(), // deprecated
removeListener: vi.fn(), // deprecated
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
})
This does not appear to work.
2
Answers
The solution was to add the following to my
setupTests.js
instead,It looks like you’re setting up the mock for window.matchMedia correctly, but there are a couple of things you can check and tweak to make it work.
Make sure that your setupTests.js is properly set up to be included in the Jest testing environment.
Also since you mentioned vi.fn(), you’re likely using Vite’s vitest instead of Jest. In this case, ensure that you have correctly imported vi from vitest