-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.test.ts
88 lines (68 loc) · 2.32 KB
/
index.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
import {retry, wait} from '.'
test('retry resolved promise', async () => {
const fn = jest.fn((...args) => Promise.resolve(args))
const args = [1, 2, 3]
const result = await retry(fn)(...args)
expect(result).toEqual(args)
expect(fn).toHaveBeenCalledTimes(1)
})
test('retry rejected and last resolved promise', async () => {
let counter = 0
const fn = jest.fn((...args) =>
counter++ > 1 ? Promise.resolve(args) : Promise.reject(new Error('error'))
)
const args = [1, 2, 3]
const result = await retry(fn, {retries: 3, timeout: 10})(...args)
expect(result).toEqual(args)
expect(fn).toHaveBeenCalledTimes(3)
})
test('retry rejected and ignore rejected with specific error', async () => {
let counter = 0
const fn = jest.fn(() =>
Promise.reject(
new Error(counter++ > 0 ? 'aborted by timeout' : 'yet another error')
)
)
const error = await retry(fn, {
retries: 3,
timeout: 10,
shouldRetry: (error) => !error.toString().match(/aborted/)
})().catch((error) => error)
expect(error.message).toBe('aborted by timeout')
expect(fn).toHaveBeenCalledTimes(2)
})
test('retry rejected promise', async () => {
const fn = jest.fn(() => Promise.reject(new Error('failed')))
const error = await retry(fn, {retries: 3, timeout: 10})().catch(
(error) => error
)
expect(error.message).toBe('failed')
expect(fn).toHaveBeenCalledTimes(3)
})
test('abort retry', async () => {
const abortController = new AbortController()
const fn = jest.fn(() => Promise.reject(new Error('failed')))
const promise = retry(fn, {
retries: 3,
timeout: 10,
signal: abortController.signal
})()
// NOTE: simulate microtask to abort wait after first attempt
await Promise.resolve().then(() => abortController.abort())
const error = await promise.catch((error) => error)
expect(error.message).toBe('The user aborted a timeout.')
expect(fn).toHaveBeenCalledTimes(1)
})
test('wait timeout', () => {
jest.useFakeTimers()
jest.spyOn(global, 'setTimeout')
const promise = wait(1000)
jest.advanceTimersByTime(1000)
expect(promise).resolves.toBeUndefined()
})
test('aborted wait timeout', () => {
const abortController = new AbortController()
const promise = wait(1000, abortController.signal)
abortController.abort()
expect(promise).rejects.toThrow('The user aborted a timeout.')
})