Jest test fails : TypeError: window.matchMedia is not a function

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(),
  })),
});

Mocking methods which are not implemented in JSDOM


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

Tags:

Reactjs

Jestjs