-
Notifications
You must be signed in to change notification settings - Fork 232
/
Copy pathsuspenseHook.test.ts
49 lines (40 loc) · 1.31 KB
/
suspenseHook.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
import { renderHook } from '../index'
describe('suspense hook tests', () => {
const cache: { value?: Promise<string | Error> | string | Error } = {}
const fetchName = (isSuccessful: boolean) => {
if (!cache.value) {
cache.value = new Promise<string>((resolve, reject) => {
setTimeout(() => {
if (isSuccessful) {
resolve('Bob')
} else {
reject(new Error('Failed to fetch name'))
}
}, 50)
})
.then((value) => (cache.value = value))
.catch((e: Error) => (cache.value = e))
}
return cache.value
}
const useFetchName = (isSuccessful = true) => {
const name = fetchName(isSuccessful)
if (name instanceof Promise || name instanceof Error) {
throw name as unknown
}
return name
}
beforeEach(() => {
delete cache.value
})
test('should allow rendering to be suspended', async () => {
const { result, waitForNextUpdate } = renderHook(() => useFetchName(true))
await waitForNextUpdate()
expect(result.current).toBe('Bob')
})
test('should set error if suspense promise rejects', async () => {
const { result, waitForNextUpdate } = renderHook(() => useFetchName(false))
await waitForNextUpdate()
expect(result.error).toEqual(new Error('Failed to fetch name'))
})
})