vitest-matchmedia-mock
TypeScript icon, indicating that this package has built-in type declarations

2.0.3 • Public • Published

Vitest MatchMediaMock

codecov NPM Version NPM Downloads

how to import:

import MatchMediaMock from 'vitest-matchmedia-mock'

Usage example

describe('your test', () => {
  let matchMediaMock = new MatchMediaMock();
  afterAll(() => {
    matchMediaMock.clear();
  });
});

Use Media Query

Example implementation

export const myImplementation = () => {
  const myMediaMatcher = window.matchMedia('(prefers-color-scheme: dark)');
  myMediaMatcher.addEventListener('change', (ev) => {
    console.log(ev.matches);
  });

  return myMediaMatcher.matches;
};

Test

describe('your test', () => {
  let matchMediaMock = new MatchMediaMock();

  afterEach(() => {
    matchMediaMock.clear();
  });

  afterAll(() => {
    matchMediaMock.destroy();
  });

  test('matches immediately', () => {
    matchMediaMock.useMediaQuery('(prefers-color-scheme: dark)');
    const response = myImplementation();

    expect(response).toBe(true);
  });

  test('doesnt match immediately', () => {
    matchMediaMock.useMediaQuery('(prefers-color-scheme: light)');
    const response = myImplementation();

    expect(response).toBe(false);
  });

  test('fires change event with match', () => {
    myImplementation();
    matchMediaMock.useMediaQuery('(prefers-color-scheme: dark)');

    expect(console.log).toHaveBeenCalledWith(true);
  });

  test('fires change event with mismatch', () => {
    myImplementation();
    matchMediaMock.useMediaQuery('(prefers-color-scheme: light)');

    expect(console.log).toHaveBeenCalledWith(false);
  });
});

Readme

Keywords

Package Sidebar

Install

npm i vitest-matchmedia-mock

Weekly Downloads

6,732

Version

2.0.3

License

ISC

Unpacked Size

12.5 kB

Total Files

5

Last publish

Collaborators

  • nggepe