skip to Main Content

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


  1. Chosen as BEST ANSWER

    The solution was to add the following to my setupTests.js instead,

    global.matchMedia = global.matchMedia || function(query) {
      return {
        matches: false,
        media: query,
        onchange: null,
        addListener: vi.fn(), // deprecated
        removeListener: vi.fn(), // deprecated
        addEventListener: vi.fn(),
        removeEventListener: vi.fn(),
        dispatchEvent: vi.fn(),
      }
    }
    
    

  2. 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.

    module.exports = { setupFilesAfterEnv: ['<rootDir>/setupTests.js'] };
    

    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

    import { vi } from 'vitest';
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search