|
| 1 | +import { createElement, FunctionComponent, StrictMode } from 'react'; |
| 2 | +import { render } from 'react-dom'; |
| 3 | +import { act } from 'react-dom/test-utils'; |
| 4 | + |
| 5 | +import { usePrefersReducedData } from '.'; |
| 6 | +import matchMediaMock from './__mocks__/matchMedia'; |
| 7 | + |
| 8 | +describe('usePrefersReducedData hook', () => { |
| 9 | + let container: HTMLDivElement; |
| 10 | + |
| 11 | + beforeEach(() => { |
| 12 | + container = document.createElement('div'); |
| 13 | + document.body.appendChild(container); |
| 14 | + }); |
| 15 | + |
| 16 | + afterEach(() => { |
| 17 | + container.remove(); |
| 18 | + container = null; |
| 19 | + }); |
| 20 | + |
| 21 | + it('should return false on the initial call', () => { |
| 22 | + let matches: boolean; |
| 23 | + |
| 24 | + const TestComponent: FunctionComponent = () => { |
| 25 | + matches = usePrefersReducedData(); |
| 26 | + return null; |
| 27 | + }; |
| 28 | + |
| 29 | + act(() => { |
| 30 | + render( |
| 31 | + createElement(StrictMode, {}, createElement(TestComponent)), |
| 32 | + container |
| 33 | + ); |
| 34 | + }); |
| 35 | + |
| 36 | + expect(matches).toBe(false); |
| 37 | + }); |
| 38 | + |
| 39 | + it('should returns true with matchMedia mocked', () => { |
| 40 | + window.matchMedia = jest.fn((media) => |
| 41 | + matchMediaMock(media, '(prefers-reduced-data: reduce)') |
| 42 | + ); |
| 43 | + |
| 44 | + let matches: boolean; |
| 45 | + const TestComponent: FunctionComponent = () => { |
| 46 | + matches = usePrefersReducedData(); |
| 47 | + return null; |
| 48 | + }; |
| 49 | + |
| 50 | + act(() => { |
| 51 | + render( |
| 52 | + createElement(StrictMode, {}, createElement(TestComponent)), |
| 53 | + document.createElement('div') |
| 54 | + ); |
| 55 | + }); |
| 56 | + |
| 57 | + expect(matches).toBe(true); |
| 58 | + }); |
| 59 | +}); |
0 commit comments