|
1 | 1 | import { StrictMode, useEffect, useRef } from 'react' |
2 | 2 | import type { PropsWithChildren } from 'react' |
3 | | -import { render, screen, waitFor } from '@testing-library/react' |
| 3 | +import { act, render, screen, waitFor } from '@testing-library/react' |
4 | 4 | import userEvent from '@testing-library/user-event' |
5 | | -import { it } from 'vitest' |
| 5 | +import { expect, it } from 'vitest' |
6 | 6 | import { useAtomValue, useSetAtom } from 'jotai/react' |
7 | 7 | import { atom } from 'jotai/vanilla' |
8 | 8 |
|
@@ -119,3 +119,36 @@ it('useSetAtom with write without an argument', async () => { |
119 | 119 | screen.getByText('count: 1') |
120 | 120 | }) |
121 | 121 | }) |
| 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