Skip to content

Commit 9f373a2

Browse files
committed
✅ test: useOnlineStatus 테스트 코드 추가
1 parent a01381f commit 9f373a2

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

src/hooks/useOnlineStatus.test.ts

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import { act, renderHook } from '@testing-library/react';
2+
import useOnlineStatus from './useOnlineStatus';
3+
4+
let windowSpy: jest.SpyInstance;
5+
let onlineCallback: jest.Mock;
6+
let offlineCallback: jest.Mock;
7+
8+
describe('useOnlineStatus', () => {
9+
beforeEach(() => {
10+
windowSpy = jest.spyOn(global, 'window', 'get');
11+
onlineCallback = jest.fn();
12+
offlineCallback = jest.fn();
13+
});
14+
15+
afterEach(() => {
16+
windowSpy.mockRestore();
17+
});
18+
19+
test('온라인 상태라면 isOnline은 true이다.', () => {
20+
jest.spyOn(navigator, 'onLine', 'get').mockReturnValueOnce(true);
21+
22+
const { result } = renderHook(() => useOnlineStatus());
23+
24+
expect(result.current.isOnline).toBe(true);
25+
});
26+
27+
test('오프라인 상태에서 isOnline은 false이다.', () => {
28+
jest.spyOn(navigator, 'onLine', 'get').mockReturnValueOnce(false);
29+
30+
const { result } = renderHook(() => useOnlineStatus());
31+
32+
expect(result.current.isOnline).toBe(false);
33+
});
34+
35+
test('네트워크 상태가 변경되면 isOnline 상태가 갱신된다.', () => {
36+
const { result } = renderHook(() => useOnlineStatus());
37+
38+
act(() => {
39+
window.dispatchEvent(new Event('offline'));
40+
});
41+
42+
expect(result.current.isOnline).toBe(false);
43+
44+
act(() => {
45+
window.dispatchEvent(new Event('online'));
46+
});
47+
48+
expect(result.current.isOnline).toBe(true);
49+
});
50+
51+
test('콜백 함수가 호출되는지 확인', () => {
52+
renderHook(() => useOnlineStatus({ onlineCallback, offlineCallback }));
53+
act(() => {
54+
window.dispatchEvent(new Event('offline'));
55+
});
56+
57+
expect(offlineCallback).toHaveBeenCalledTimes(1);
58+
59+
act(() => {
60+
window.dispatchEvent(new Event('online'));
61+
});
62+
expect(onlineCallback).toHaveBeenCalledTimes(1);
63+
});
64+
65+
test('언마운트 시 이벤트 리스너가 제거된다.', () => {
66+
const { unmount } = renderHook(() =>
67+
useOnlineStatus({ onlineCallback, offlineCallback })
68+
);
69+
70+
unmount();
71+
72+
act(() => {
73+
window.dispatchEvent(new Event('offline'));
74+
});
75+
expect(offlineCallback).toHaveBeenCalledTimes(0);
76+
77+
act(() => {
78+
window.dispatchEvent(new Event('online'));
79+
});
80+
expect(onlineCallback).toHaveBeenCalledTimes(0);
81+
});
82+
});

0 commit comments

Comments
 (0)