Skip to content

Commit 0c47d51

Browse files
authored
Merge branch 'main' into test/react-useSetAtom-readonly
2 parents a59684c + 8d74967 commit 0c47d51

File tree

1 file changed

+92
-2
lines changed

1 file changed

+92
-2
lines changed

tests/react/useAtomValue.test.tsx

Lines changed: 92 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
import { StrictMode } from 'react'
2-
import { render, screen } from '@testing-library/react'
1+
import { Component, StrictMode, Suspense } from 'react'
2+
import type { ReactNode } from 'react'
3+
import { act, render, screen } from '@testing-library/react'
34
import userEvent from '@testing-library/user-event'
45
import { it } from 'vitest'
56
import { useAtomValue, useSetAtom } from 'jotai/react'
@@ -30,3 +31,92 @@ it('useAtomValue basic test', async () => {
3031
await userEvent.click(screen.getByText('dispatch'))
3132
await screen.findByText('count: 1')
3233
})
34+
35+
it('useAtomValue with async atom (promise)', async () => {
36+
const asyncAtom = atom(async () => 42)
37+
38+
const AsyncComponent = () => {
39+
const value = useAtomValue(asyncAtom)
40+
41+
return <div>value: {value}</div>
42+
}
43+
44+
await act(async () => {
45+
render(
46+
<StrictMode>
47+
<Suspense fallback="loading">
48+
<AsyncComponent />
49+
</Suspense>
50+
</StrictMode>,
51+
)
52+
})
53+
54+
await screen.findByText('value: 42')
55+
})
56+
57+
class ErrorBoundary extends Component<
58+
{ children: ReactNode },
59+
{ error: Error | null }
60+
> {
61+
constructor(props: { children: ReactNode }) {
62+
super(props)
63+
64+
this.state = { error: null }
65+
}
66+
67+
static getDerivedStateFromError(error: Error) {
68+
return { error }
69+
}
70+
71+
render() {
72+
if (this.state.error) {
73+
return <div>error: {this.state.error.message}</div>
74+
}
75+
76+
return this.props.children
77+
}
78+
}
79+
80+
it('useAtomValue with error throwing atom', async () => {
81+
const errorAtom = atom(() => {
82+
throw new Error('fail')
83+
})
84+
85+
const ErrorComponent = () => {
86+
useAtomValue(errorAtom)
87+
88+
return <div>no error</div>
89+
}
90+
91+
render(
92+
<StrictMode>
93+
<ErrorBoundary>
94+
<ErrorComponent />
95+
</ErrorBoundary>
96+
</StrictMode>,
97+
)
98+
99+
await screen.findByText('error: fail')
100+
})
101+
102+
it('useAtomValue with atom returning object', async () => {
103+
const objAtom = atom({ a: 1, b: 2 })
104+
105+
const ObjComponent = () => {
106+
const value = useAtomValue(objAtom)
107+
108+
return (
109+
<div>
110+
obj: {value.a},{value.b}
111+
</div>
112+
)
113+
}
114+
115+
render(
116+
<StrictMode>
117+
<ObjComponent />
118+
</StrictMode>,
119+
)
120+
121+
await screen.findByText('obj: 1,2')
122+
})

0 commit comments

Comments
 (0)