-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
index.test.ts
104 lines (85 loc) · 2.77 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
import { type InjectionKey, type Ref, defineComponent, h, inject, nextTick, ref } from 'vue-demi'
import { createInjectionState, injectLocal } from '@vueuse/shared'
import { describe, expect, it } from 'vitest'
import { mount, useSetup } from '../../.test'
describe('createInjectionState', () => {
it('should work for simple nested component', async () => {
const [useProvideCountState, useCountState] = createInjectionState((initialValue: number) => {
const count = ref(initialValue)
return count
})
let count: Ref<number> | undefined
const ChildComponent = defineComponent({
setup() {
count = useCountState()
return () => h('div')
},
})
const RootComponent = defineComponent({
setup() {
useProvideCountState(114514)
return () => h(ChildComponent)
},
})
const vm = mount(RootComponent)
await nextTick()
expect(count?.value).toBe(114514)
vm.unmount()
})
it('should work for custom key', async () => {
const KEY: InjectionKey<Ref<number>> = Symbol('count-state')
const [useProvideCountState, useCountState] = createInjectionState((initialValue: number) => {
const count = ref(initialValue)
return count
}, { injectionKey: KEY })
let count: Ref<number> | undefined
let count2: Ref<number> | undefined
const ChildComponent = defineComponent({
setup() {
count = useCountState()
count2 = inject(KEY)
return () => h('div')
},
})
const RootComponent = defineComponent({
setup() {
useProvideCountState(0)
return () => h(ChildComponent)
},
})
const vm = mount(RootComponent)
await nextTick()
expect(count?.value).toBe(0)
expect(count2?.value).toBe(0)
vm.unmount()
})
it('allow call useProvidingState and useInjectedState in same component', async () => {
const [useProvideCountState, useCountState] = createInjectionState((initialValue: number) => {
const count = ref(initialValue)
return count
})
const vm = useSetup(() => {
useProvideCountState(114514)
const count = useCountState()!
return { count }
})
await nextTick()
expect(vm.count).toBe(114514)
vm.unmount()
})
it('allow call useProvidingState and injectLocal in same component', async () => {
const KEY: InjectionKey<Ref<number>> | string = Symbol('count-state')
const [useProvideCountState] = createInjectionState((initialValue: number) => {
const count = ref(initialValue)
return count
}, { injectionKey: KEY })
const vm = useSetup(() => {
useProvideCountState(114514)
const count = injectLocal(KEY)!
return { count }
})
await nextTick()
expect(vm.count).toBe(114514)
vm.unmount()
})
})