Fix Jest "window.matchMedia is not a function"

Published on · Updated on
3 min read.
Tags: JavaScriptJestUnit testing

If you're testing React components that use window.matchMedia, Jest will crash with TypeError: window.matchMedia is not a function. This browser API doesn't exist in the jsdom test environment.

Why it happens

Jest runs tests in Node.js with jsdom, which doesn't implement window.matchMedia. Any code that calls matchMedia (common in responsive components, media query hooks, dark-mode toggles, or UI libraries) will fail.

The fix

Add this mock to your Jest setup file:

// jest.setup.ts
Object.defineProperty(window, 'matchMedia', {
  writable: true,
  value: (query: string) => ({
    matches: false,
    media: query,
    onchange: null,
    addListener: () => {},
    removeListener: () => {},
    addEventListener: () => {},
    removeEventListener: () => {},
    dispatchEvent: () => false,
  }),
});

and make sure Jest loads it:

// jest.config.ts
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],

addListener and removeListener are the deprecated versions of addEventListener and removeEventListener. Some libraries still call them, so the mock includes both.

Getting "Cannot read properties of undefined (reading 'matches')"?

That happens when the mock is a jest.fn().mockImplementation(...) and your config has resetMocks: true (Create React App turns it on by default). Jest resets every mock before each test, which removes the implementation, so matchMedia() returns undefined. The plain function above isn't a Jest mock, so the reset doesn't touch it.

Make it return true for specific queries

If a test needs matches: true, override matchMedia with the queries that should match:

function mockMatchMedia(matchingQueries: string[]) {
  window.matchMedia = (query: string) => ({
    matches: matchingQueries.includes(query),
    media: query,
    onchange: null,
    addListener: () => {},
    removeListener: () => {},
    addEventListener: () => {},
    removeEventListener: () => {},
    dispatchEvent: () => false,
  });
}

it('shows the sidebar on desktop', () => {
  mockMatchMedia(['(min-width: 768px)']);
  render(<Layout />);
  expect(screen.getByRole('navigation')).toBeInTheDocument();
});

The query string has to match what your component passes to matchMedia character for character, including spaces.

Vitest

Vitest with environment: "jsdom" has the same gap. The plain-function mock works unchanged; put it in the file listed under test.setupFiles.