window.matchMedia is not a function code example

Example: window.matchMedia is not a function

/*See the official ject work around to mock this out for use in unit test*/
/*matchMedia.js mock file*/
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(),
  })),
});
/*---------------------------*/
import './matchMedia.mock'; // Must be imported before the tested file
import {myMethod} from './file-to-test';

describe('should test this methhod  that use matchmedia', () => {
  // Test the method here...
});

Tags:

Misc Example