Skip to content

Commit 951b457

Browse files
committed
test(react/useSetAtom): add test for throwing error when called with read-only atom
1 parent aabd4af commit 951b457

File tree

1 file changed

+44
-3
lines changed

1 file changed

+44
-3
lines changed

tests/react/useSetAtom.test.tsx

Lines changed: 44 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,16 @@
11
import { StrictMode, useEffect, useRef } from 'react'
22
import type { PropsWithChildren } from 'react'
3-
import { render, screen, waitFor } from '@testing-library/react'
3+
import {
4+
act,
5+
render,
6+
renderHook,
7+
screen,
8+
waitFor,
9+
} from '@testing-library/react'
410
import userEvent from '@testing-library/user-event'
5-
import { it } from 'vitest'
11+
import { expect, it, vi } from 'vitest'
612
import { useAtomValue, useSetAtom } from 'jotai/react'
7-
import { atom } from 'jotai/vanilla'
13+
import { type Atom, type WritableAtom, atom } from 'jotai/vanilla'
814

915
const useCommitCount = () => {
1016
const commitCountRef = useRef(1)
@@ -119,3 +125,38 @@ it('useSetAtom with write without an argument', async () => {
119125
screen.getByText('count: 1')
120126
})
121127
})
128+
129+
it('useSetAtom throws when called with a read-only atom', () => {
130+
const originalEnv = import.meta.env
131+
Object.defineProperty(import.meta, 'env', {
132+
value: { MODE: 'development' },
133+
writable: true,
134+
})
135+
const originalMode = process.env.MODE
136+
process.env.MODE = 'development'
137+
138+
const countAtom = atom(0)
139+
const readOnlyAtom = atom((get) => get(countAtom))
140+
141+
let setAtomFn: ((v: number) => void) | undefined
142+
143+
function TestComponent() {
144+
// eslint-disable-next-line react-hooks/react-compiler
145+
setAtomFn = useSetAtom(readOnlyAtom as any)
146+
return null
147+
}
148+
149+
render(<TestComponent />)
150+
151+
expect(() => {
152+
act(() => {
153+
setAtomFn?.(1)
154+
})
155+
}).toThrowError('not writable atom')
156+
157+
Object.defineProperty(import.meta, 'env', {
158+
value: originalEnv,
159+
writable: true,
160+
})
161+
process.env.MODE = originalMode
162+
})

0 commit comments

Comments
 (0)