-
-
Notifications
You must be signed in to change notification settings - Fork 565
/
transition.test.tsx
110 lines (94 loc) 路 2.97 KB
/
transition.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
103
104
105
106
107
108
109
110
import { StrictMode, Suspense, useEffect, useTransition } from 'react'
import { fireEvent, render } from '@testing-library/react'
import { atom, useAtom, useAtomValue, useSetAtom } from 'jotai'
import { getTestProvider } from './testUtils'
const Provider = getTestProvider()
const describeWithUseTransition =
typeof useTransition === 'function' ? describe : describe.skip
describeWithUseTransition('useTransition', () => {
it('no extra commit with useTransition (#1125)', async () => {
const countAtom = atom(0)
const delayedAtom = atom(async (get) => {
await new Promise((r) => setTimeout(r, 100))
return get(countAtom)
})
const commited: { pending: boolean; delayed: number }[] = []
const Counter = () => {
const setCount = useSetAtom(countAtom)
const delayed = useAtomValue(delayedAtom)
const [pending, startTransition] = useTransition()
useEffect(() => {
commited.push({ pending, delayed })
})
return (
<>
<div>delayed: {delayed}</div>
<button onClick={() => startTransition(() => setCount((c) => c + 1))}>
button
</button>
</>
)
}
const { getByText, findByText } = render(
<>
<Provider>
<Suspense fallback="loading">
<Counter />
</Suspense>
</Provider>
</>
)
await findByText('delayed: 0')
await new Promise((r) => setTimeout(r, 100))
fireEvent.click(getByText('button'))
await findByText('delayed: 1')
await new Promise((r) => setTimeout(r, 100))
expect(commited).toEqual([
{ pending: false, delayed: 0 },
{ pending: true, delayed: 0 },
{ pending: false, delayed: 1 },
])
})
it('can update normal atom with useTransition (#1151)', async () => {
const countAtom = atom(0)
const toggleAtom = atom(false)
const pendingAtom = atom((get) => {
if (get(toggleAtom)) {
return new Promise(() => {})
}
return false
})
const Counter = () => {
const [count, setCount] = useAtom(countAtom)
const toggle = useSetAtom(toggleAtom)
useAtomValue(pendingAtom)
const [pending, startTransition] = useTransition()
return (
<>
<div>count: {count}</div>
<button onClick={() => setCount((c) => c + 1)}>increment</button>
{pending && 'pending'}
<button onClick={() => startTransition(() => toggle((x) => !x))}>
toggle
</button>
</>
)
}
const { getByText, findByText } = render(
<StrictMode>
<Provider>
<Suspense fallback="loading">
<Counter />
</Suspense>
</Provider>
</StrictMode>
)
await findByText('count: 0')
fireEvent.click(getByText('toggle'))
await findByText('pending')
fireEvent.click(getByText('increment'))
await findByText('count: 1')
fireEvent.click(getByText('increment'))
await findByText('count: 2')
})
})