-
Notifications
You must be signed in to change notification settings - Fork 273
/
Copy pathwait-for.test.tsx
318 lines (253 loc) · 9.05 KB
/
wait-for.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
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
import * as React from 'react';
import { Pressable, Text, TouchableOpacity, View } from 'react-native';
import { configure, fireEvent, render, screen, waitFor } from '..';
class Banana extends React.Component<any> {
changeFresh = () => {
this.props.onChangeFresh();
};
render() {
return (
<View>
{this.props.fresh && <Text>Fresh</Text>}
<TouchableOpacity onPress={this.changeFresh}>
<Text>Change freshness!</Text>
</TouchableOpacity>
</View>
);
}
}
class BananaContainer extends React.Component<object, any> {
state = { fresh: false };
onChangeFresh = async () => {
await new Promise((resolve) => setTimeout(resolve, 300));
this.setState({ fresh: true });
};
render() {
return <Banana onChangeFresh={this.onChangeFresh} fresh={this.state.fresh} />;
}
}
afterEach(() => {
jest.useRealTimers();
});
test('waits for element until it stops throwing', async () => {
render(<BananaContainer />);
fireEvent.press(screen.getByText('Change freshness!'));
expect(screen.queryByText('Fresh')).toBeNull();
const freshBananaText = await waitFor(() => screen.getByText('Fresh'));
expect(freshBananaText.props.children).toBe('Fresh');
});
test('waits for element until timeout is met', async () => {
render(<BananaContainer />);
fireEvent.press(screen.getByText('Change freshness!'));
await expect(waitFor(() => screen.getByText('Fresh'), { timeout: 100 })).rejects.toThrow();
// Async action ends after 300ms and we only waited 100ms, so we need to wait
// for the remaining async actions to finish
await waitFor(() => screen.getByText('Fresh'));
});
test('waitFor defaults to asyncWaitTimeout config option', async () => {
configure({ asyncUtilTimeout: 100 });
render(<BananaContainer />);
fireEvent.press(screen.getByText('Change freshness!'));
await expect(waitFor(() => screen.getByText('Fresh'))).rejects.toThrow();
// Async action ends after 300ms and we only waited 100ms, so we need to wait
// for the remaining async actions to finish
await waitFor(() => screen.getByText('Fresh'), { timeout: 1000 });
});
test('waitFor timeout option takes precendence over `asyncWaitTimeout` config option', async () => {
configure({ asyncUtilTimeout: 2000 });
render(<BananaContainer />);
fireEvent.press(screen.getByText('Change freshness!'));
await expect(waitFor(() => screen.getByText('Fresh'), { timeout: 100 })).rejects.toThrow();
// Async action ends after 300ms and we only waited 100ms, so we need to wait
// for the remaining async actions to finish
await waitFor(() => screen.getByText('Fresh'));
});
test('waits for element with custom interval', async () => {
const mockFn = jest.fn(() => {
throw Error('test');
});
try {
await waitFor(() => mockFn(), { timeout: 400, interval: 200 });
} catch {
// suppress
}
expect(mockFn).toHaveBeenCalledTimes(2);
});
// this component is convoluted on purpose. It is not a good react pattern, but it is valid
// react code that will run differently between different react versions (17 and 18), so we need
// explicit tests for it
const Comp = ({ onPress }: { onPress: () => void }) => {
const [state, setState] = React.useState(false);
React.useEffect(() => {
if (state) {
onPress();
}
}, [state, onPress]);
return (
<Pressable
onPress={async () => {
await Promise.resolve();
setState(true);
}}
>
<Text>Trigger</Text>
</Pressable>
);
};
test('waits for async event with fireEvent', async () => {
const spy = jest.fn();
render(<Comp onPress={spy} />);
fireEvent.press(screen.getByText('Trigger'));
await waitFor(() => {
expect(spy).toHaveBeenCalled();
});
});
test.each([false, true])(
'waits for element until it stops throwing using fake timers (legacyFakeTimers = %s)',
async (legacyFakeTimers) => {
jest.useFakeTimers({ legacyFakeTimers });
render(<BananaContainer />);
fireEvent.press(screen.getByText('Change freshness!'));
expect(screen.queryByText('Fresh')).toBeNull();
jest.advanceTimersByTime(300);
const freshBananaText = await waitFor(() => screen.getByText('Fresh'));
expect(freshBananaText.props.children).toBe('Fresh');
},
);
test.each([false, true])(
'waits for assertion until timeout is met with fake timers (legacyFakeTimers = %s)',
async (legacyFakeTimers) => {
jest.useFakeTimers({ legacyFakeTimers });
const mockFn = jest.fn(() => {
throw Error('test');
});
try {
await waitFor(() => mockFn(), { timeout: 400, interval: 200 });
} catch {
// suppress
}
expect(mockFn).toHaveBeenCalledTimes(3);
},
);
test.each([false, true])(
'waits for assertion until timeout is met with fake timers (legacyFakeTimers = %s)',
async (legacyFakeTimers) => {
jest.useFakeTimers({ legacyFakeTimers });
const mockErrorFn = jest.fn(() => {
throw Error('test');
});
const mockHandleFn = jest.fn((e) => e);
try {
await waitFor(() => mockErrorFn(), {
timeout: 400,
interval: 200,
onTimeout: mockHandleFn,
});
} catch {
// suppress
}
expect(mockErrorFn).toHaveBeenCalledTimes(3);
expect(mockHandleFn).toHaveBeenCalledTimes(1);
},
);
const blockThread = (timeToBlockThread: number, legacyFakeTimers: boolean) => {
jest.useRealTimers();
const end = Date.now() + timeToBlockThread;
while (Date.now() < end) {
// do nothing
}
jest.useFakeTimers({ legacyFakeTimers });
};
test.each([true, false])(
'it should not depend on real time when using fake timers (legacyFakeTimers = %s)',
async (legacyFakeTimers) => {
jest.useFakeTimers({ legacyFakeTimers });
const WAIT_FOR_INTERVAL = 20;
const WAIT_FOR_TIMEOUT = WAIT_FOR_INTERVAL * 5;
const mockErrorFn = jest.fn(() => {
// Wait 2 times interval so that check time is longer than interval
blockThread(WAIT_FOR_INTERVAL * 2, legacyFakeTimers);
throw new Error('test');
});
await expect(
async () =>
await waitFor(mockErrorFn, {
timeout: WAIT_FOR_TIMEOUT,
interval: WAIT_FOR_INTERVAL,
}),
).rejects.toThrow();
// Verify that the `waitFor` callback has been called the expected number of times
// (timeout / interval + 1), so it confirms that the real duration of callback did not
// cause the real clock timeout when running using fake timers.
expect(mockErrorFn).toHaveBeenCalledTimes(WAIT_FOR_TIMEOUT / WAIT_FOR_INTERVAL + 1);
},
);
test.each([false, true])(
'awaiting something that succeeds before timeout works with fake timers (legacyFakeTimers = %s)',
async (legacyFakeTimers) => {
jest.useFakeTimers({ legacyFakeTimers });
let calls = 0;
const mockFn = jest.fn(() => {
calls += 1;
if (calls < 3) {
throw Error('test');
}
});
try {
await waitFor(() => mockFn(), { timeout: 400, interval: 200 });
} catch {
// suppress
}
expect(mockFn).toHaveBeenCalledTimes(3);
},
);
test.each([
[false, false],
[true, false],
[true, true],
])(
'flushes scheduled updates before returning (fakeTimers = %s, legacyFakeTimers = %s)',
async (fakeTimers, legacyFakeTimers) => {
if (fakeTimers) {
jest.useFakeTimers({ legacyFakeTimers });
}
function Apple({ onPress }: { onPress: (color: string) => void }) {
const [color, setColor] = React.useState('green');
const [syncedColor, setSyncedColor] = React.useState(color);
// On mount, set the color to "red" in a promise microtask
React.useEffect(() => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises, promise/catch-or-return, promise/prefer-await-to-then
Promise.resolve('red').then((c) => setColor(c));
}, []);
// Sync the `color` state to `syncedColor` state, but with a delay caused by the effect
React.useEffect(() => {
setSyncedColor(color);
}, [color]);
return (
<View testID="root">
<Text>{color}</Text>
<Pressable onPress={() => onPress(syncedColor)}>
<Text>Trigger</Text>
</Pressable>
</View>
);
}
const onPress = jest.fn();
render(<Apple onPress={onPress} />);
// Required: this `waitFor` will succeed on first check, because the "root" view is there
// since the initial mount.
await waitFor(() => screen.getByTestId('root'));
// This `waitFor` will also succeed on first check, because the promise that sets the
// `color` state to "red" resolves right after the previous `await waitFor` statement.
await waitFor(() => screen.getByText('red'));
// Check that the `onPress` callback is called with the already-updated value of `syncedColor`.
fireEvent.press(screen.getByText('Trigger'));
expect(onPress).toHaveBeenCalledWith('red');
},
);
test('waitFor throws if expectation is not a function', async () => {
await expect(
// @ts-expect-error intentionally passing non-function
waitFor('not a function'),
).rejects.toThrowErrorMatchingInlineSnapshot(`"Received \`expectation\` arg must be a function"`);
});