-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
index.test.ts
73 lines (64 loc) · 2.04 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
import { promiseTimeout } from '@vueuse/shared'
import { useAsyncState } from '../useAsyncState'
describe('useAsyncState', () => {
it('should be defined', () => {
expect(useAsyncState).toBeDefined()
})
const p1 = (num = 1) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve(num)
}, 50)
})
}
const p2 = async (id?: string) => {
if (!id)
throw new Error('error')
return id
}
it('should work', async () => {
const { execute, state } = useAsyncState(p1, 0)
expect(state.value).toBe(0)
await execute(0, 2)
expect(state.value).toBe(2)
})
it('should work with isLoading', () => {
const { execute, isLoading } = useAsyncState(p1, 0, { immediate: false })
expect(isLoading.value).toBeFalsy()
execute(1)
expect(isLoading.value).toBeTruthy()
})
it('should work with isReady', async () => {
const { execute, isReady } = useAsyncState(p1, 0, { immediate: false })
expect(isReady.value).toBeFalsy()
await execute(1)
expect(isReady.value).toBeTruthy()
})
it('should work with error', async () => {
const { execute, error } = useAsyncState(p2, '0', { immediate: false })
expect(error.value).toBeUndefined()
await execute()
expect(error.value).toBeInstanceOf(Error)
})
it('should work with delay', async () => {
const { execute, state } = useAsyncState(p1, 0, { delay: 100 })
await promiseTimeout(50)
expect(state.value).toBe(0)
await execute(0, 2)
expect(state.value).toBe(2)
})
it('should work with onSuccess', async () => {
const onSuccess = vi.fn()
const { execute } = useAsyncState(p1, 0, { onSuccess })
await execute(0, 2)
expect(onSuccess).toHaveBeenCalled()
expect(onSuccess).toHaveBeenCalledWith(2)
})
it('should work with onError', async () => {
const onError = vi.fn()
const { execute } = useAsyncState(p2, '0', { onError, immediate: false })
await execute()
expect(onError).toHaveBeenCalled()
expect(onError).toHaveBeenCalledWith(new Error('error'))
})
})