-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuse-query.test.ts
258 lines (195 loc) · 9.1 KB
/
use-query.test.ts
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
import { act, fireEvent, renderHook } from '@testing-library/react';
import { type QueryFn, type QueryOptions, useQuery, useStableQueryKey } from './use-query.js';
describe('useStableQueryKey', () => {
const key = [1, { b: 1, c: 'string', a: { f: true, d: null, e: undefined } }];
it('should JSON serialize', () => {
const { result } = renderHook(() => useStableQueryKey(key));
expect(result.current).toEqual(JSON.parse(JSON.stringify(key)));
});
it('should order object keys', () => {
const { result } = renderHook(() => useStableQueryKey(key));
expect(result.current).toMatchInlineSnapshot(`
[
1,
{
"a": {
"d": null,
"f": true,
},
"b": 1,
"c": "string",
},
]
`);
});
});
describe('useQuery', () => {
let queryFnMock: any;
beforeEach(() => {
queryFnMock = vi.fn().mockResolvedValue('foo');
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it('should query on mount and not on rerender', async () => {
const { result, rerender } = renderHook((props: { key: unknown[] } = { key: ['a'] }) =>
useQuery(props.key, queryFnMock),
);
expect(queryFnMock).toHaveBeenCalledTimes(1);
expect(result.current.isFetching).toEqual(true);
expect(result.current.data).toBeUndefined();
expect(result.current.error).toBeUndefined();
await act(() => vi.waitFor(() => !result.current.isFetching));
expect(result.current.data).toEqual('foo');
expect(result.current.error).toBeUndefined();
rerender();
expect(queryFnMock).toHaveBeenCalledTimes(1);
expect(result.current.isFetching).toEqual(false);
});
it('should query on key change', async () => {
const { result, rerender } = renderHook((props: { key: unknown[] } = { key: ['a'] }) =>
useQuery(props.key, queryFnMock),
);
expect(queryFnMock).toHaveBeenCalledTimes(1);
expect(result.current.isFetching).toEqual(true);
await act(() => vi.waitFor(() => !result.current.isFetching));
expect(result.current.data).toEqual('foo');
expect(result.current.error).toBeUndefined();
// Should clear data immediately if the key changes.
// NOTE: Setting up error for later.
queryFnMock.mockRejectedValueOnce(new Error('error'));
rerender({ key: [{ a: 1 }] });
expect(queryFnMock).toHaveBeenCalledTimes(2);
expect(result.current.data).toBeUndefined();
await act(() => vi.waitFor(() => !result.current.isFetching));
// Should clear error immediately if the key changes.
expect(result.current.error).toBeInstanceOf(Error);
rerender({ key: [{ a: 1, b: 2 }] });
expect(queryFnMock).toHaveBeenCalledTimes(3);
expect(result.current.error).toBeUndefined();
await act(() => vi.waitFor(() => !result.current.isFetching));
rerender({ key: [{ b: 2, a: 1 }] });
// Property order isn't a key "change"
expect(queryFnMock).toHaveBeenCalledTimes(3);
await act(() => vi.waitFor(() => !result.current.isFetching));
});
it('should query when imperatively triggered', async () => {
const { result } = renderHook(() => useQuery(['a'], queryFnMock));
expect(queryFnMock).toHaveBeenCalledTimes(1);
expect(result.current.isFetching).toEqual(true);
await act(() => vi.waitFor(() => !result.current.isFetching));
expect(result.current.data).toEqual('foo');
// Should keep previous data, because the key didn't change.
act(() => result.current.refetch());
expect(queryFnMock).toHaveBeenCalledTimes(2);
expect(result.current.data).toEqual('foo');
await act(() => vi.waitFor(() => !result.current.isFetching));
expect(result.current.data).toEqual('foo');
// Keep the data if an error occurs too.
queryFnMock.mockRejectedValueOnce(new Error('error'));
act(() => result.current.refetch());
expect(queryFnMock).toHaveBeenCalledTimes(3);
expect(result.current.data).toEqual('foo');
await act(() => vi.waitFor(() => !result.current.isFetching));
expect(result.current.data).toEqual('foo');
expect(result.current.error).toBeInstanceOf(Error);
// Error is cleared when the query succeeds.
act(() => result.current.refetch());
await act(() => vi.waitFor(() => !result.current.isFetching));
expect(result.current.data).toEqual('foo');
expect(result.current.error).toBeUndefined();
});
it('should query when the refresh interval elapses', async () => {
const { result } = renderHook(() => useQuery([], queryFnMock, { refetchInterval: 1000 }));
expect(queryFnMock).toHaveBeenCalledTimes(1);
expect(result.current.isFetching).toEqual(true);
await act(() => vi.waitFor(() => !result.current.isFetching));
// Not elapsed yet.
act(() => void vi.advanceTimersByTime(500));
expect(queryFnMock).toHaveBeenCalledTimes(1);
// Now the refetch interval has elapsed, so refetch should be in progress.
act(() => void vi.advanceTimersByTime(501));
expect(queryFnMock).toHaveBeenCalledTimes(2);
await act(() => vi.waitFor(() => !result.current.isFetching));
});
it('should query when reconnected', async () => {
const { result, rerender } = renderHook((options: QueryOptions) => useQuery([], queryFnMock, options));
expect(queryFnMock).toHaveBeenCalledTimes(1);
expect(result.current.isFetching).toEqual(true);
await act(() => vi.waitFor(() => !result.current.isFetching));
act(() => void fireEvent(window, new Event('online')));
expect(queryFnMock).toHaveBeenCalledTimes(2);
// Not when already fetching.
act(() => void fireEvent(window, new Event('online')));
expect(queryFnMock).toHaveBeenCalledTimes(2);
await act(() => vi.waitFor(() => !result.current.isFetching));
// Not when disabled
rerender({ refetchOnReconnect: false });
act(() => void fireEvent(window, new Event('online')));
expect(queryFnMock).toHaveBeenCalledTimes(2);
await act(() => vi.waitFor(() => !result.current.isFetching));
});
it('should query when the window is focused', async () => {
const { result, rerender } = renderHook((options: QueryOptions) => useQuery([], queryFnMock, options));
expect(queryFnMock).toHaveBeenCalledTimes(1);
expect(result.current.isFetching).toEqual(true);
await act(() => vi.waitFor(() => !result.current.isFetching));
act(() => void fireEvent(window, new Event('focus')));
expect(queryFnMock).toHaveBeenCalledTimes(2);
// Not when already fetching.
act(() => void fireEvent(window, new Event('focus')));
expect(queryFnMock).toHaveBeenCalledTimes(2);
await act(() => vi.waitFor(() => !result.current.isFetching));
// Not when disabled
rerender({ refetchOnWindowFocus: false });
act(() => void fireEvent(window, new Event('focus')));
expect(queryFnMock).toHaveBeenCalledTimes(2);
await act(() => vi.waitFor(() => !result.current.isFetching));
});
it('should cancel the previous query when a new query starts', async () => {
const { result, rerender } = renderHook((key: unknown[] = ['a']) => useQuery(key, queryFnMock));
expect(queryFnMock).toHaveBeenCalledTimes(1);
// Manual refetch
act(() => result.current.refetch());
expect(queryFnMock).toHaveBeenCalledTimes(2);
expect(queryFnMock.mock.calls.at(-2)?.[0].signal.aborted).toEqual(true);
// NOT on manual refetch with cancelRefetch set to false.
act(() => result.current.refetch({ cancelRefetch: false }));
expect(queryFnMock).toHaveBeenCalledTimes(2);
// Key change refetch
rerender(['b']);
expect(queryFnMock).toHaveBeenCalledTimes(3);
expect(queryFnMock.mock.calls.at(-2)?.[0].signal.aborted).toEqual(true);
await act(() => vi.waitFor(() => !result.current.isFetching));
});
it('should always use the most recent query function instance', async () => {
const queryFnUpdate = vi.fn().mockResolvedValue('bar');
const { result, rerender } = renderHook((queryFn: QueryFn = queryFnMock) => useQuery(['a'], queryFn));
expect(queryFnMock).toHaveBeenCalledTimes(1);
// Changing the function shouldn't cause a refetch.
rerender(queryFnUpdate);
expect(queryFnMock).toHaveBeenCalledTimes(1);
// The next fetch should use the updated query function.
act(() => result.current.refetch());
expect(queryFnMock).toHaveBeenCalledTimes(1);
expect(queryFnUpdate).toHaveBeenCalledTimes(1);
await act(() => vi.waitFor(() => !result.current.isFetching));
});
it('should abort fetch on unmount', async () => {
const { unmount } = renderHook(() => useQuery(['a'], queryFnMock));
expect(queryFnMock).toHaveBeenCalledTimes(1);
unmount();
expect(queryFnMock.mock.calls.at(-1)?.[0].signal.aborted).toEqual(true);
});
it('should unmount without error when no query is running', async () => {
vi.useRealTimers();
const { result, unmount } = renderHook(() => useQuery(['a'], queryFnMock));
await act(() => vi.waitFor(() => !result.current.isFetching));
expect(queryFnMock).toHaveBeenCalledTimes(1);
expect(queryFnMock.mock.calls.at(-1)?.[0].signal.aborted).toEqual(false);
unmount();
// Wait for all awaited promises to resolve.
await new Promise((resolve) => setTimeout(resolve));
});
});