JavaScript, React, TypeScript, Web Development

Jest – React Testing – window.matchMedia is not a function

Jest – React Testing – window.matchMedia is not a function

The other day, I was writing a test for an Ant Design’s Avatar component. The test keeps failing because of the following error:

TypeError: window.matchMedia is not a function

It seems that the third party component listens to DOM events for its responsive design. Jest’s official workaround for this doesn’t work in our case.

https://jestjs.io/docs/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom

Is this because we are using TypeScript? Our workaround is to modify the polyfill a bit and it works so far.

// ./src/setupDomTests.ts

// Dummy import so that the linter won't complain
import { render } from '@testing-library/react'

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

Since we need to apply it to all of our tests, we just include it in our setupTests.ts file.

// ./src/setupTests.ts
import '@testing-library/jest-dom';
import './setupDomTests';

Now, all our tests are running smoothly.

Featured image by Andrea Piacquadio.