Skip to content

Commit 111a596

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

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

tests/react/useSetAtom.test.tsx

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import { StrictMode, useEffect, useRef } from 'react'
22
import type { PropsWithChildren } from 'react'
3-
import { render, screen, waitFor } from '@testing-library/react'
3+
import { act, render, screen, waitFor } from '@testing-library/react'
44
import userEvent from '@testing-library/user-event'
5-
import { it } from 'vitest'
5+
import { expect, it } from 'vitest'
66
import { useAtomValue, useSetAtom } from 'jotai/react'
77
import { atom } from 'jotai/vanilla'
88

@@ -119,3 +119,36 @@ it('useSetAtom with write without an argument', async () => {
119119
screen.getByText('count: 1')
120120
})
121121
})
122+
123+
it('useSetAtom throws when called with a read-only atom', () => {
124+
const originalEnv = import.meta.env
125+
126+
Object.defineProperty(import.meta, 'env', {
127+
value: { MODE: 'development' },
128+
writable: true,
129+
})
130+
131+
const countAtom = atom(0)
132+
const readOnlyAtom = atom((get) => get(countAtom))
133+
134+
let setAtomFn: ((v: number) => void) | undefined
135+
136+
function TestComponent() {
137+
// eslint-disable-next-line react-hooks/react-compiler
138+
setAtomFn = useSetAtom(readOnlyAtom as any)
139+
return null
140+
}
141+
142+
render(<TestComponent />)
143+
144+
expect(() => {
145+
act(() => {
146+
setAtomFn?.(1)
147+
})
148+
}).toThrowError('not writable atom')
149+
150+
Object.defineProperty(import.meta, 'env', {
151+
value: originalEnv,
152+
writable: true,
153+
})
154+
})

0 commit comments

Comments
 (0)