I am using tinyMCE in my project while testing the tinyMCE component. I am facing the error
window.matchMedia is not a function
in the import of import 'tinymce/tinymce';
in my test file, I tried to mock it with
beforeAll(() => {
server.listen();
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(),
}))
});
});
but still getting the same error.
How to mock so that the node_modules libs use the mock windows object?
Look at https://jestjs.io/docs/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom.
If window.matchMedia() is executed directly in the tested file, Jest reports the same error. In this case, the solution is to move the manual mock into a separate file and include this one in the test before the tested file:
This means somewhere there is invocation of the matchMedia
method but since you mocked it within a specific test file, it complains.
One way to handle this is to move this piece of code within a separate setupJestMocks.js
and add that within the setupFiles
of jestConfig.js
. Details here https://jestjs.io/docs/configuration#setupfiles-array