|
| 1 | +import React from 'react' |
| 2 | +import isMatching from 'css-mediaquery' |
| 3 | +import { render, RenderResult } from '@testing-library/react' |
| 4 | +import { useMatchMediaQuery } from '../useMatchMediaQuery' |
| 5 | + |
| 6 | +beforeEach(() => { |
| 7 | + // mock window.matchMedia (use 'css-mediaquery') |
| 8 | + window.matchMedia = jest.fn().mockImplementation((query) => { |
| 9 | + return { |
| 10 | + addListener: jest.fn(), |
| 11 | + media: query, |
| 12 | + matches: isMatching.match(query, { |
| 13 | + width: 500, |
| 14 | + }), |
| 15 | + } |
| 16 | + }) |
| 17 | +}) |
| 18 | + |
| 19 | +const TestComponent = ({ query }: { query: string }) => { |
| 20 | + const isMatched = useMatchMediaQuery(query) |
| 21 | + if (isMatched) return <div>visible</div> |
| 22 | + return <div>hidden</div> |
| 23 | +} |
| 24 | + |
| 25 | +function renderTestComponent(query: string): RenderResult { |
| 26 | + return render(<TestComponent query={query} />) |
| 27 | +} |
| 28 | + |
| 29 | +describe('useReactSimpleMatchMedia', () => { |
| 30 | + it('should be visible when min width matches', () => { |
| 31 | + const { getByText } = renderTestComponent('(min-width : 500px)') |
| 32 | + expect(getByText(/visible/i)).toBeInTheDocument() |
| 33 | + }) |
| 34 | + |
| 35 | + it('should not be visible min does not match', () => { |
| 36 | + const { getByText } = renderTestComponent('(min-width : 600px)') |
| 37 | + expect(getByText(/hidden/i)).toBeInTheDocument() |
| 38 | + }) |
| 39 | + |
| 40 | + it('should be visible if between matches', () => { |
| 41 | + const { getByText } = renderTestComponent( |
| 42 | + '(min-width : 500px) and (max-width: 600px)' |
| 43 | + ) |
| 44 | + expect(getByText(/visible/i)).toBeInTheDocument() |
| 45 | + }) |
| 46 | +}) |
0 commit comments