-
Notifications
You must be signed in to change notification settings - Fork 232
/
Copy pathasyncHook.fakeTimers.test.ts
77 lines (61 loc) · 2 KB
/
asyncHook.fakeTimers.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
import * as React from 'react'
describe('async hook (fake timers) tests', () => {
beforeEach(() => {
jest.useFakeTimers()
})
afterEach(() => {
jest.useRealTimers()
})
runForRenderers(['default', 'dom', 'native', 'server/hydrated'], ({ renderHook }) => {
test('should wait for arbitrary expectation to pass when using advanceTimersByTime()', async () => {
const { waitFor } = renderHook(() => null)
let actual = 0
const expected = 1
setTimeout(() => {
actual = expected
}, 200)
let complete = false
await waitFor(() => {
expect(actual).toBe(expected)
complete = true
})
expect(complete).toBe(true)
})
test('it waits for the data to be loaded using', async () => {
const fetchAMessage = () =>
new Promise((resolve) => {
// we are using random timeout here to simulate a real-time example
// of an async operation calling a callback at a non-deterministic time
const randomTimeout = Math.floor(Math.random() * 100)
setTimeout(() => {
resolve({ returnedMessage: 'Hello World' })
}, randomTimeout)
})
function useLoader() {
const [state, setState] = React.useState<{ data: unknown; loading: boolean }>({
data: undefined,
loading: true
})
React.useEffect(() => {
let cancelled = false
fetchAMessage().then((data) => {
if (!cancelled) {
setState({ data, loading: false })
}
})
return () => {
cancelled = true
}
}, [])
return state
}
const { result, waitFor } = renderHook(() => useLoader())
expect(result.current).toEqual({ data: undefined, loading: true })
await waitFor(() => {
expect(result.current).toEqual({ data: { returnedMessage: 'Hello World' }, loading: false })
})
})
})
})
// eslint-disable-next-line jest/no-export
export {}