forked from Nova-reward/Nova-Rewards
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusePolling.test.ts
More file actions
114 lines (85 loc) · 2.66 KB
/
Copy pathusePolling.test.ts
File metadata and controls
114 lines (85 loc) · 2.66 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import { renderHook, act, waitFor } from '@testing-library/react';
import { usePolling } from '../usePolling';
describe('usePolling', () => {
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
it('should fetch data on mount', async () => {
const mockFetch = jest.fn().mockResolvedValue({ data: 'test' });
renderHook(() => usePolling({
fetchFn: mockFetch,
interval: 15000,
}));
expect(mockFetch).toHaveBeenCalledTimes(1);
});
it('should poll at specified interval', async () => {
const mockFetch = jest.fn().mockResolvedValue({ data: 'test' });
renderHook(() => usePolling({
fetchFn: mockFetch,
interval: 15000,
}));
expect(mockFetch).toHaveBeenCalledTimes(1);
act(() => {
jest.advanceTimersByTime(15000);
});
await waitFor(() => {
expect(mockFetch).toHaveBeenCalledTimes(2);
});
});
it('should pause polling when tab is hidden', () => {
const mockFetch = jest.fn().mockResolvedValue({ data: 'test' });
renderHook(() => usePolling({
fetchFn: mockFetch,
interval: 15000,
}));
expect(mockFetch).toHaveBeenCalledTimes(1);
// Hide tab
Object.defineProperty(document, 'visibilityState', { value: 'hidden', configurable: true });
document.dispatchEvent(new Event('visibilitychange'));
act(() => {
jest.advanceTimersByTime(15000);
});
// Should not have fetched again
expect(mockFetch).toHaveBeenCalledTimes(1);
});
it('should implement exponential backoff on failure', async () => {
const mockFetch = jest.fn().mockRejectedValue(new Error('Failed'));
renderHook(() => usePolling({
fetchFn: mockFetch,
interval: 15000,
maxRetries: 3,
retryDelay: 1000,
}));
expect(mockFetch).toHaveBeenCalledTimes(1);
// Should retry after 1 second
act(() => {
jest.advanceTimersByTime(1000);
});
await waitFor(() => {
expect(mockFetch).toHaveBeenCalledTimes(2);
});
// Should retry after 2 seconds
act(() => {
jest.advanceTimersByTime(2000);
});
await waitFor(() => {
expect(mockFetch).toHaveBeenCalledTimes(3);
});
});
it('should stop polling on unmount', () => {
const mockFetch = jest.fn().mockResolvedValue({ data: 'test' });
const { unmount } = renderHook(() => usePolling({
fetchFn: mockFetch,
interval: 15000,
}));
expect(mockFetch).toHaveBeenCalledTimes(1);
unmount();
act(() => {
jest.advanceTimersByTime(15000);
});
expect(mockFetch).toHaveBeenCalledTimes(1);
});
});