forked from vueuse/vueuse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.test.ts
97 lines (86 loc) · 2.61 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
89
90
91
92
93
94
95
96
97
import { nextTick, reactive, ref } from 'vue-demi'
import { watchTriggerable } from '.'
describe('watchTriggerable', () => {
test('this should work', async () => {
const source = ref(0)
const effect = ref(0)
let cleanupCount = -1
const { trigger } = watchTriggerable(source, (value, oldValue, onCleanup) => {
onCleanup(() => {
cleanupCount = value
})
expect(value).toBe(source.value)
effect.value = value
})
// By default watch will be executed on the next tick
source.value = 1
expect(effect.value).toBe(0)
await nextTick()
expect(effect.value).toBe(source.value)
expect(cleanupCount).toBe(-1)
source.value = 2
expect(cleanupCount).toBe(-1)
await nextTick()
expect(effect.value).toBe(source.value)
expect(cleanupCount).toBe(1)
// trigger is executed immediately
effect.value = 0
trigger()
expect(effect.value).toBe(source.value)
expect(cleanupCount).toBe(2)
})
test('source array', async () => {
const source1 = ref(0)
const source2 = reactive({ a: 'a' })
const effect1 = ref(-1)
const effect2 = ref('z')
let cleanupCount = -1
const { trigger } = watchTriggerable([source1, () => source2.a], ([value1, value2], [old1, old2], onCleanup) => {
onCleanup(() => {
cleanupCount = value1
})
expect(value1).toBe(source1.value)
effect1.value = value1
effect2.value = value2
})
trigger()
expect(effect1.value).toBe(source1.value)
expect(effect2.value).toBe(source2.a)
expect(cleanupCount).toBe(-1)
source1.value = 1
source2.a = 'b'
await nextTick()
expect(effect1.value).toBe(source1.value)
expect(effect2.value).toBe(source2.a)
expect(cleanupCount).toBe(0)
})
test('source reactive object', async () => {
const source = reactive({ a: 'a' })
const effect = ref('')
let cleanupCount = 0
const { trigger } = watchTriggerable(source, (value, old, onCleanup) => {
onCleanup(() => {
cleanupCount += 1
})
expect(value).toBe(source)
effect.value = value.a
})
trigger()
expect(effect.value).toBe(source.a)
expect(cleanupCount).toBe(0)
source.a = 'b'
await nextTick()
expect(effect.value).toBe(source.a)
expect(cleanupCount).toBe(1)
})
test('trigger should await', async () => {
const source = ref(1)
const effect = ref(0)
const { trigger } = watchTriggerable(source, async (value) => {
await new Promise(resolve => setTimeout(resolve, 10))
effect.value = value
})
await trigger()
expect(effect.value).toBe(source.value)
})
})