forked from callstack/react-native-testing-library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
waitFor.test.js
95 lines (73 loc) · 2.2 KB
/
waitFor.test.js
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
// @flow
import React from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import { render, fireEvent, 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<{}, 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} />
);
}
}
test('waits for element until it stops throwing', async () => {
const { getByText, queryByText } = render(<BananaContainer />);
fireEvent.press(getByText('Change freshness!'));
expect(queryByText('Fresh')).toBeNull();
const freshBananaText = await waitFor(() => getByText('Fresh'));
expect(freshBananaText.props.children).toBe('Fresh');
});
test('waits for element until timeout is met', async () => {
const { getByText } = render(<BananaContainer />);
fireEvent.press(getByText('Change freshness!'));
await expect(
waitFor(() => 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(() => 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 (e) {
// suppress
}
expect(mockFn).toHaveBeenCalledTimes(3);
});
test('works with fake timers', async () => {
jest.useFakeTimers();
const mockFn = jest.fn(() => {
throw Error('test');
});
try {
waitFor(() => mockFn(), { timeout: 400, interval: 200 });
} catch (e) {
// suppress
}
jest.runTimersToTime(400);
expect(mockFn).toHaveBeenCalledTimes(3);
jest.useRealTimers();
});