|
| 1 | +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +import React, { useRef } from 'react'; |
| 5 | +import { act, render } from '@testing-library/react'; |
| 6 | + |
| 7 | +import { useMobile } from '../index'; |
| 8 | + |
| 9 | +function Demo() { |
| 10 | + const renderCount = useRef(0); |
| 11 | + const isMobile = useMobile(); |
| 12 | + renderCount.current++; |
| 13 | + return ( |
| 14 | + <div> |
| 15 | + <span data-testid="mobile">{String(isMobile)}</span> |
| 16 | + <span data-testid="render-count">{renderCount.current}</span> |
| 17 | + </div> |
| 18 | + ); |
| 19 | +} |
| 20 | + |
| 21 | +function resizeWindow(width: number) { |
| 22 | + act(() => { |
| 23 | + Object.defineProperty(window, 'innerWidth', { value: width }); |
| 24 | + window.dispatchEvent(new CustomEvent('resize')); |
| 25 | + }); |
| 26 | +} |
| 27 | + |
| 28 | +test('should report mobile width on the initial render', () => { |
| 29 | + resizeWindow(400); |
| 30 | + const { getByTestId } = render(<Demo />); |
| 31 | + expect(getByTestId('mobile').textContent).toBe('true'); |
| 32 | +}); |
| 33 | + |
| 34 | +test('should report desktop width on the initial render', () => { |
| 35 | + resizeWindow(1200); |
| 36 | + const { getByTestId } = render(<Demo />); |
| 37 | + expect(getByTestId('mobile').textContent).toBe('false'); |
| 38 | +}); |
| 39 | + |
| 40 | +test('should report the updated value after resize', () => { |
| 41 | + resizeWindow(400); |
| 42 | + const { getByTestId } = render(<Demo />); |
| 43 | + const countBefore = getByTestId('render-count').textContent; |
| 44 | + resizeWindow(1200); |
| 45 | + const countAfter = getByTestId('render-count').textContent; |
| 46 | + expect(getByTestId('mobile').textContent).toBe('false'); |
| 47 | + expect(countBefore).not.toEqual(countAfter); |
| 48 | +}); |
| 49 | + |
| 50 | +test('no renders when resize does not hit the breakpoint', () => { |
| 51 | + resizeWindow(1000); |
| 52 | + const { getByTestId } = render(<Demo />); |
| 53 | + const countBefore = getByTestId('render-count').textContent; |
| 54 | + resizeWindow(1200); |
| 55 | + const countAfter = getByTestId('render-count').textContent; |
| 56 | + expect(countBefore).toEqual(countAfter); |
| 57 | +}); |
0 commit comments