-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
index.test.ts
106 lines (87 loc) · 2.84 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
98
99
100
101
102
103
104
105
106
import type { Ref } from 'vue-demi'
import { nextTick, ref } from 'vue-demi'
import { describe, expect, it } from 'vitest'
import { useSetup } from '../../.test'
import { toValue } from '../toValue'
import { whenever } from '.'
describe('whenever', () => {
const expectType = <T>(value: T) => value
it('ignore falsy state change', async () => {
// use a component to simulate normal use case
const vm = useSetup(() => {
const number = ref<number | null | undefined>(1)
const changeNumber = (v: number) => number.value = v
const watchCount = ref(0)
const watchValue: Ref<number | undefined> = ref()
whenever(number, (value) => {
watchCount.value += 1
watchValue.value = value
expectType<number>(value)
// @ts-expect-error value should be of type number
expectType<undefined>(value)
// @ts-expect-error value should be of type number
expectType<null>(value)
// @ts-expect-error value should be of type number
expectType<string>(value)
})
return {
number,
watchCount,
watchValue,
changeNumber,
}
})
expect(toValue(vm.watchCount)).toEqual(0)
vm.changeNumber(2)
await nextTick()
expect(toValue(vm.watchCount)).toEqual(1)
expect(toValue(vm.watchValue)).toEqual(2)
vm.changeNumber(0)
await nextTick()
expect(toValue(vm.watchCount)).toEqual(1)
expect(toValue(vm.watchValue)).toEqual(2)
vm.changeNumber(3)
await nextTick()
expect(toValue(vm.watchCount)).toEqual(2)
expect(toValue(vm.watchValue)).toEqual(3)
vm.unmount()
})
it('once', async () => {
const vm = useSetup(() => {
const number = ref<number | null | undefined>(1)
const watchCount = ref(0)
const watchValue: Ref<number | undefined> = ref()
whenever(number, (value) => {
watchCount.value += 1
watchValue.value = value
expectType<number>(value)
// @ts-expect-error value should be of type number
expectType<undefined>(value)
// @ts-expect-error value should be of type number
expectType<null>(value)
// @ts-expect-error value should be of type number
expectType<string>(value)
}, { once: true })
const changeNumber = (v: number) => number.value = v
return {
number,
watchCount,
watchValue,
changeNumber,
}
})
vm.changeNumber(0)
await nextTick()
expect(toValue(vm.watchCount)).toEqual(0)
expect(toValue(vm.watchValue)).toBeUndefined()
vm.changeNumber(1)
await nextTick()
expect(toValue(vm.watchCount)).toEqual(1)
expect(toValue(vm.watchValue)).toEqual(1)
vm.changeNumber(2)
await nextTick()
expect(toValue(vm.watchCount)).toEqual(1)
expect(toValue(vm.watchValue)).toEqual(1)
vm.unmount()
})
})