-
Notifications
You must be signed in to change notification settings - Fork 1
/
WindowWidth.test.tsx
48 lines (38 loc) · 1.42 KB
/
WindowWidth.test.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import React from 'react';
import { render, cleanup, screen, waitFor } from '@testing-library/react';
import WindowWidth, { handleResize } from '../WindowWidth';
describe('[Testing effects] WindowWidth', () => {
beforeAll(() => {
// Mock window.addEventListener and window.removeEventListener
global.addEventListener = jest.fn();
global.removeEventListener = jest.fn();
});
afterEach(cleanup);
test('call setWidth on resize', () => {
const setWidth = jest.fn();
const resizeHandler = handleResize(setWidth);
// Simulate window resize
global.innerWidth = 500;
resizeHandler();
expect(setWidth).toHaveBeenCalledWith(500);
});
test('attaches resize listener on mount', () => {
render(<WindowWidth />);
expect(global.addEventListener).toHaveBeenCalledWith('resize', expect.any(Function));
});
test('removes resize listener on unmount', () => {
const { unmount } = render(<WindowWidth />);
unmount();
expect(global.removeEventListener).toHaveBeenCalledWith('resize', expect.any(Function));
});
test('updates width on resize', async () => {
render(<WindowWidth />);
// Change the innerWidth property and dispatch a resize event
global.innerWidth = 500;
global.dispatchEvent(new Event('resize'));
// Wait for the state update to occur
await waitFor(() => {
expect(screen.getByText('Window width: 500')).toBeInTheDocument();
});
});
});