Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

useMutation-semantics.test.tsx

337 lines10.7 KB

1// useMutation on core `action`: each mutate() is one transaction. Transient
2// flight state is an optimistic overlay (auto-drops at settle); durable state
3// commits post-yield atomically with invalidation-triggered refetches;
4// query-core supplies retry/offline/scope policy through
5// mutationCache.build().execute(). One mutate, returning a safe-to-ignore
6// promise. onMutate is the optimistic-overlay window β€” no context, no
7// rollback plumbing.
8import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
9import { Loading, createOptimistic, createRenderEffect } from 'solid-js'
10import { createKey, sleep } from '@tanstack/query-test-utils'
11import { QueryCache, QueryClient, useMutation, useQuery } from '..'
12import { renderWithClient } from './utils'
13​
14describe('useMutation 2.0 semantics', () => {
15 let queryCache: QueryCache
16 let queryClient: QueryClient
17​
18 beforeEach(() => {
19 vi.useFakeTimers()
20 queryCache = new QueryCache()
21 queryClient = new QueryClient({ queryCache })
22 })
23​
24 afterEach(() => {
25 queryClient.clear()
26 vi.useRealTimers()
27 })
28​
29 it('shows pending during flight and lands data on success', async () => {
30 function Page() {
31 const mutation = useMutation(() => ({
32 mutationFn: (name: string) => sleep(10).then(() => `hello ${name}`),
33 }))
34 return (
35 <div>
36 <span>
37 status: {mutation.status}, data: {mutation.data ?? 'none'}
38 </span>
39 <button onClick={() => mutation.mutate('world')}>go</button>
40 </div>
41 )
42 }
43​
44 const rendered = renderWithClient(queryClient, () => <Page />)
45 expect(rendered.getByText('status: idle, data: none')).toBeInTheDocument()
46​
47 rendered.getByRole('button').click()
48 await vi.advanceTimersByTimeAsync(0)
49 expect(
50 rendered.getByText('status: pending, data: none'),
51 ).toBeInTheDocument()
52​
53 await vi.advanceTimersByTimeAsync(10)
54 expect(
55 rendered.getByText('status: success, data: hello world'),
56 ).toBeInTheDocument()
57 })
58​
59 it('routes errors to state; the ignored promise never surfaces as unhandled', async () => {
60 function Page() {
61 const mutation = useMutation(() => ({
62 mutationFn: () =>
63 sleep(10).then(() => Promise.reject(new Error('nope'))),
64 }))
65 return (
66 <div>
67 <span>
68 status: {mutation.status}, error:{' '}
69 {mutation.error?.message ?? 'none'}
70 </span>
71 <button onClick={() => mutation.mutate()}>go</button>
72 </div>
73 )
74 }
75​
76 const rendered = renderWithClient(queryClient, () => <Page />)
77 rendered.getByRole('button').click()
78 await vi.advanceTimersByTimeAsync(10)
79 expect(rendered.getByText('status: error, error: nope')).toBeInTheDocument()
80 })
81​
82 it('awaiting mutate rejects with the mutation error', async () => {
83 let caught: unknown
84 function Page() {
85 const mutation = useMutation(() => ({
86 mutationFn: () =>
87 sleep(5).then(() => Promise.reject(new Error('boom'))),
88 }))
89 return (
90 <button
91 onClick={() => {
92 mutation.mutate().catch((error) => {
93 caught = error
94 })
95 }}
96 >
97 go
98 </button>
99 )
100 }
101​
102 const rendered = renderWithClient(queryClient, () => <Page />)
103 rendered.getByRole('button').click()
104 await vi.advanceTimersByTimeAsync(5)
105 expect((caught as Error).message).toBe('boom')
106 })
107​
108 it('onMutate optimistic overlay shows during flight and reverts on failure', async () => {
109 const key = createKey()
110 queryClient.setQueryData(key, 'alice')
111​
112 function Page() {
113 const [draft, setDraft] = createOptimistic<string | null>(null)
114 const query = useQuery(() => ({
115 queryKey: key,
116 queryFn: () => sleep(5).then(() => 'alice'),
117 staleTime: 60_000,
118 }))
119 const mutation = useMutation(() => ({
120 mutationFn: (_name: string) =>
121 sleep(10).then(() => Promise.reject(new Error('rejected'))),
122 onMutate: (name) => setDraft(name),
123 }))
124 return (
125 <div>
126 <span>name: {draft() ?? query.data}</span>
127 <button onClick={() => mutation.mutate('bob')}>rename</button>
128 </div>
129 )
130 }
131​
132 const rendered = renderWithClient(queryClient, () => (
133 <Loading fallback={<span>loading</span>}>
134 <Page />
135 </Loading>
136 ))
137 expect(rendered.getByText('name: alice')).toBeInTheDocument()
138​
139 rendered.getByRole('button').click()
140 await vi.advanceTimersByTimeAsync(0)
141 expect(rendered.getByText('name: bob')).toBeInTheDocument()
142​
143 // Failure settles the transition; the overlay drops with nothing
144 // durable behind it β€” automatic rollback.
145 await vi.advanceTimersByTimeAsync(10)
146 expect(rendered.getByText('name: alice')).toBeInTheDocument()
147 })
148​
149 it('onMutate overlay + onSuccess cache write hand off without a gap', async () => {
150 const key = createKey()
151 queryClient.setQueryData(key, 'alice')
152​
153 function Page() {
154 const [draft, setDraft] = createOptimistic<string | null>(null)
155 const query = useQuery(() => ({
156 queryKey: key,
157 queryFn: () => sleep(5).then(() => 'alice'),
158 staleTime: 60_000,
159 }))
160 const mutation = useMutation(() => ({
161 mutationFn: (name: string) => sleep(10).then(() => name),
162 onMutate: (name) => setDraft(name),
163 onSuccess: (name, _vars, _result, context) => {
164 context.client.setQueryData(key, name)
165 },
166 }))
167 return (
168 <div>
169 <span>name: {draft() ?? query.data}</span>
170 <button onClick={() => mutation.mutate('bob')}>rename</button>
171 </div>
172 )
173 }
174​
175 const rendered = renderWithClient(queryClient, () => (
176 <Loading fallback={<span>loading</span>}>
177 <Page />
178 </Loading>
179 ))
180​
181 rendered.getByRole('button').click()
182 await vi.advanceTimersByTimeAsync(0)
183 expect(rendered.getByText('name: bob')).toBeInTheDocument()
184​
185 // The overlay drops in the same settle that commits the cache write:
186 // never a frame showing 'alice' again.
187 await vi.advanceTimersByTimeAsync(10)
188 expect(rendered.getByText('name: bob')).toBeInTheDocument()
189 })
190​
191 it('settles atomically with invalidation-triggered refetches', async () => {
192 const key = createKey()
193 let serverCount = 0
194 const commits: Array<string> = []
195​
196 function Page() {
197 const query = useQuery(() => ({
198 queryKey: key,
199 queryFn: () => sleep(5).then(() => serverCount),
200 staleTime: 60_000,
201 }))
202 const mutation = useMutation(() => ({
203 mutationFn: () =>
204 sleep(10).then(() => {
205 serverCount++
206 }),
207 onSuccess: (_data, _vars, _result, context) => {
208 void context.client.invalidateQueries({ queryKey: key })
209 },
210 }))
211 createRenderEffect(
212 () => `${query.data}:${mutation.isPending}`,
213 (pair) => {
214 commits.push(pair)
215 },
216 )
217 return (
218 <div>
219 <span>
220 count: {query.data}, pending: {String(mutation.isPending)}
221 </span>
222 <button onClick={() => mutation.mutate()}>increment</button>
223 </div>
224 )
225 }
226​
227 const rendered = renderWithClient(queryClient, () => (
228 <Loading fallback={<span>loading</span>}>
229 <Page />
230 </Loading>
231 ))
232 await vi.advanceTimersByTimeAsync(5)
233 expect(rendered.getByText('count: 0, pending: false')).toBeInTheDocument()
234​
235 rendered.getByRole('button').click()
236 // Mutation in flight: pending overlay visible, data unchanged.
237 await vi.advanceTimersByTimeAsync(0)
238 expect(rendered.getByText('count: 0, pending: true')).toBeInTheDocument()
239​
240 // Mutation succeeds at +10ms, invalidation refetch needs +5ms more.
241 // The settle holds until fresh data lands, and the optimistic frame
242 // releases once nothing authoritative is left to wait on β€” fresh data
243 // and the lifted overlay commit in ONE frame. The invariant: stale
244 // data is never paired with a settled mutation β€” (0, false) never
245 // reappears, and (1, true) is not a frame either.
246 await vi.advanceTimersByTimeAsync(20)
247 expect(rendered.getByText('count: 1, pending: false')).toBeInTheDocument()
248 expect(commits).toStrictEqual(['0:false', '0:true', '1:false'])
249 })
250​
251 it('reset returns to idle', async () => {
252 function Page() {
253 const mutation = useMutation(() => ({
254 mutationFn: () => sleep(5).then(() => 'done'),
255 }))
256 return (
257 <div>
258 <span>status: {mutation.status}</span>
259 <button onClick={() => mutation.mutate()}>go</button>
260 <button onClick={() => mutation.reset()}>reset</button>
261 </div>
262 )
263 }
264​
265 const rendered = renderWithClient(queryClient, () => <Page />)
266 rendered.getByText('go').click()
267 await vi.advanceTimersByTimeAsync(5)
268 expect(rendered.getByText('status: success')).toBeInTheDocument()
269​
270 rendered.getByText('reset').click()
271 await vi.advanceTimersByTimeAsync(0)
272 expect(rendered.getByText('status: idle')).toBeInTheDocument()
273 })
274​
275 it('runs scoped mutations serially through query-core', async () => {
276 const order: Array<string> = []
277 function Page() {
278 const mutation = useMutation(() => ({
279 mutationFn: (id: string) => {
280 order.push(`start:${id}`)
281 return sleep(10).then(() => {
282 order.push(`end:${id}`)
283 return id
284 })
285 },
286 scope: { id: 'serial' },
287 }))
288 return (
289 <button
290 onClick={() => {
291 mutation.mutate('a')
292 mutation.mutate('b')
293 }}
294 >
295 go
296 </button>
297 )
298 }
299​
300 const rendered = renderWithClient(queryClient, () => <Page />)
301 rendered.getByRole('button').click()
302 await vi.advanceTimersByTimeAsync(30)
303 expect(order).toStrictEqual(['start:a', 'end:a', 'start:b', 'end:b'])
304 })
305​
306 it('applies query-core retry policy', async () => {
307 let attempts = 0
308 function Page() {
309 const mutation = useMutation(() => ({
310 mutationFn: () => {
311 attempts++
312 return sleep(5).then(() =>
313 attempts < 2 ? Promise.reject(new Error('flaky')) : 'recovered',
314 )
315 },
316 retry: 1,
317 retryDelay: 5,
318 }))
319 return (
320 <div>
321 <span>
322 status: {mutation.status}, data: {mutation.data ?? 'none'}
323 </span>
324 <button onClick={() => mutation.mutate()}>go</button>
325 </div>
326 )
327 }
328​
329 const rendered = renderWithClient(queryClient, () => <Page />)
330 rendered.getByRole('button').click()
331 await vi.advanceTimersByTimeAsync(30)
332 expect(attempts).toBe(2)
333 expect(
334 rendered.getByText('status: success, data: recovered'),
335 ).toBeInTheDocument()
336 })
337})