-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.test.tsx
100 lines (81 loc) · 2.51 KB
/
index.test.tsx
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
import React, { Component as ReactComponent } from 'react'
import { createCleanupRef } from '../cleanup-ref'
import { UNSTABLE_createHocInterface } from '.'
interface CounterState { counter: number }
function withCounter(Component) {
class WithCounter extends ReactComponent<Record<string, never>, CounterState> {
state = { counter: 0 }
render() {
return (
<Component
state={[
this.state,
this.setState.bind(this),
// Will get error if we don't bind it here.
// "Cannot read property 'updater' of undefined"
// See: https://github.com/facebook/react/issues/9654#issuecomment-300659423
]}
/>
)
}
increaseCounter = () => {
this.setState((oldState) => ({
...oldState,
counter: oldState.counter + 1,
}))
}
}
return WithCounter
}
test(UNSTABLE_createHocInterface.name, async (): Promise<void> => {
const cleanupRef = createCleanupRef()
const chi = UNSTABLE_createHocInterface({
entry: ({ Component }) => withCounter(Component),
actions: {
increaseCounter: ({ props }) => {
const [, setState] = props.state
setState((oldState: CounterState) => ({
...oldState,
counter: oldState.counter + 1,
}))
},
},
values: {
value: (({ props }) => {
const [state] = props.state
return state.counter
}),
},
}, cleanupRef)
// Initial state
expect(chi.getRenderCount()).toBe(1)
expect(chi.get('value')).toBe(0)
// After increment
chi.actions('increaseCounter')
chi.actions('increaseCounter')
chi.actions('increaseCounter')
expect(chi.getRenderCount()).toBe(4)
expect(chi.get('value')).toBe(3)
// Batched increment
chi.actions('increaseCounter', 'increaseCounter', 'increaseCounter')
expect(chi.getRenderCount()).toBe(5)
expect(chi.get('value')).toBe(6)
// Batched increment
await chi.actionsAsync('increaseCounter', 'increaseCounter', 'increaseCounter')
expect(chi.getRenderCount()).toBe(8)
expect(chi.get('value')).toBe(9)
// Non-existent action
expect(() => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error Ignored on purpose to test the error
chi.actions(['abc'])
}).toThrow()
// Non-existent values
expect(() => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error Ignored on purpose to test the error
chi.get('abc')
}).toThrow()
// Cleanup
cleanupRef.run()
})