Vitest MatchMediaMock
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);
});
});