|
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 { |
| 4 | + act, |
| 5 | + render, |
| 6 | + renderHook, |
| 7 | + screen, |
| 8 | + waitFor, |
| 9 | +} from '@testing-library/react' |
4 | 10 | import userEvent from '@testing-library/user-event'
|
5 |
| -import { it } from 'vitest' |
| 11 | +import { expect, it, vi } from 'vitest' |
6 | 12 | import { useAtomValue, useSetAtom } from 'jotai/react'
|
7 |
| -import { atom } from 'jotai/vanilla' |
| 13 | +import { type Atom, type WritableAtom, atom } from 'jotai/vanilla' |
8 | 14 |
|
9 | 15 | const useCommitCount = () => {
|
10 | 16 | const commitCountRef = useRef(1)
|
@@ -119,3 +125,38 @@ it('useSetAtom with write without an argument', async () => {
|
119 | 125 | screen.getByText('count: 1')
|
120 | 126 | })
|
121 | 127 | })
|
| 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