-
-
Notifications
You must be signed in to change notification settings - Fork 238
/
ref.test.tsx
102 lines (86 loc) 路 2.3 KB
/
ref.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
101
102
import { StrictMode, useEffect, useRef } from 'react'
import { fireEvent, render } from '@testing-library/react'
import { proxy, ref, useSnapshot } from 'valtio'
const consoleError = console.error
beforeEach(() => {
console.error = jest.fn((message) => {
if (
process.env.NODE_ENV === 'production' &&
message.startsWith('act(...) is not supported in production')
) {
return
}
consoleError(message)
})
})
afterEach(() => {
console.error = consoleError
})
it('should trigger re-render setting objects with ref wrapper', async () => {
const obj = proxy({ nested: ref({ count: 0 }) })
const Counter = () => {
const snap = useSnapshot(obj)
const commitsRef = useRef(1)
useEffect(() => {
commitsRef.current += 1
})
return (
<>
<div>
count: {snap.nested.count} ({commitsRef.current})
</div>
<button onClick={() => (obj.nested = ref({ count: 0 }))}>button</button>
</>
)
}
const { getByText, findByText } = render(
<>
<Counter />
</>
)
await findByText('count: 0 (1)')
fireEvent.click(getByText('button'))
await findByText('count: 0 (2)')
})
it('should not track object wrapped in ref assigned to proxy state', async () => {
const obj = proxy<{ ui: JSX.Element | null }>({ ui: null })
const Component = () => {
const snap = useSnapshot(obj)
return (
<>
{snap.ui || <span>original</span>}
<button onClick={() => (obj.ui = ref(<span>replace</span>))}>
button
</button>
</>
)
}
const { getByText, findByText } = render(
<StrictMode>
<Component />
</StrictMode>
)
await findByText('original')
fireEvent.click(getByText('button'))
await findByText('replace')
})
it('should not trigger re-render when mutating object wrapped in ref', async () => {
const obj = proxy({ nested: ref({ count: 0 }) })
const Counter = () => {
const snap = useSnapshot(obj)
return (
<>
<div>count: {snap.nested.count}</div>
<button onClick={() => ++obj.nested.count}>button</button>
</>
)
}
const { getByText, findByText } = render(
<StrictMode>
<Counter />
</StrictMode>
)
await findByText('count: 0')
fireEvent.click(getByText('button'))
await findByText('count: 0')
})