Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import { QueryClient } from '@tanstack/query-core'
3import type { ReactiveController, ReactiveControllerHost } from 'lit'
4import { QueryClientProvider } from '../QueryClientProvider.js'
5import { createMutationController } from '../createMutationController.js'
6import {
7 TestControllerHost,
8 TestElementHost,
9 waitFor,
10 waitForMissingQueryClient,
11} from './testHost.js'
12β
13const providerTagName = 'test-query-client-provider-mutation'
14if (!customElements.get(providerTagName)) {
15 customElements.define(providerTagName, QueryClientProvider)
16}
17β
18let explicitMutationClient: QueryClient | undefined
19β
20class ContextMutationHostElement extends TestElementHost {
21 readonly mutationKey = ['context-mutation'] as const
22β
23 readonly mutation = createMutationController(
24 this,
25 {
26 mutationKey: this.mutationKey,
27 mutationFn: async (value: number) => value + 1,
28 },
29 explicitMutationClient,
30 )
31}
32β
33const contextMutationTagName = 'test-context-mutation-host'
34if (!customElements.get(contextMutationTagName)) {
35 customElements.define(contextMutationTagName, ContextMutationHostElement)
36}
37β
38describe('createMutationController', () => {
39 it('LC-MUT-01: first provider connection resolves from the pre-connect placeholder state', async () => {
40 const consumer = document.createElement(
41 contextMutationTagName,
42 ) as ContextMutationHostElement
43β
44 expect(consumer.mutation().isIdle).toBe(true)
45 expect(() => consumer.mutation.mutate(1)).toThrowError(
46 /No QueryClient available/,
47 )
48 await expect(consumer.mutation.mutateAsync(1)).rejects.toThrow(
49 /No QueryClient available/,
50 )
51β
52 const client = new QueryClient()
53 const provider = document.createElement(
54 providerTagName,
55 ) as QueryClientProvider
56 provider.client = client
57 provider.append(consumer)
58β
59 document.body.append(provider)
60 await provider.updateComplete
61 await Promise.resolve()
62β
63 await expect(consumer.mutation.mutateAsync(1)).resolves.toBe(2)
64 expect(consumer.mutation().isSuccess).toBe(true)
65β
66 consumer.mutation.destroy()
67 provider.remove()
68 await Promise.resolve()
69 })
70β
71 it('LC-MUT-02: explicit client takes precedence over provider context', async () => {
72 const explicitClient = new QueryClient()
73 const providerClient = new QueryClient()
74 explicitMutationClient = explicitClient
75β
76 const provider = document.createElement(
77 providerTagName,
78 ) as QueryClientProvider
79 provider.client = providerClient
80β
81 const consumer = document.createElement(
82 contextMutationTagName,
83 ) as ContextMutationHostElement
84 provider.append(consumer)
85β
86 document.body.append(provider)
87 await provider.updateComplete
88 await Promise.resolve()
89β
90 await expect(consumer.mutation.mutateAsync(2)).resolves.toBe(3)
91β
92 expect(
93 explicitClient
94 .getMutationCache()
95 .findAll({ mutationKey: consumer.mutationKey }).length,
96 ).toBeGreaterThan(0)
97 expect(
98 providerClient
99 .getMutationCache()
100 .findAll({ mutationKey: consumer.mutationKey }).length,
101 ).toBe(0)
102β
103 consumer.mutation.destroy()
104 provider.remove()
105 explicitMutationClient = undefined
106 await Promise.resolve()
107 })
108β
109 it('supports mutate and mutateAsync paths', async () => {
110 const client = new QueryClient()
111 const host = new TestControllerHost()
112β
113 const mutation = createMutationController(
114 host,
115 {
116 mutationFn: async (value: number) => value + 1,
117 },
118 client,
119 )
120β
121 host.connect()
122 host.update()
123β
124 const result = await mutation.mutateAsync(1)
125 expect(result).toBe(2)
126 expect(mutation().isSuccess).toBe(true)
127 expect(mutation().data).toBe(2)
128β
129 mutation.mutate(2)
130 await waitFor(() => mutation().data === 3)
131 expect(mutation().isSuccess).toBe(true)
132 })
133β
134 it('M9: mutation state transitions cover idle/pending/success/error', async () => {
135 const client = new QueryClient()
136 const host = new TestControllerHost()
137β
138 const mutation = createMutationController(
139 host,
140 {
141 mutationFn: async (value: number) => {
142 await new Promise((resolve) => setTimeout(resolve, 10))
143 if (value < 0) {
144 throw new Error('negative-not-allowed')
145 }
146 return value + 1
147 },
148 },
149 client,
150 )
151β
152 host.connect()
153 host.update()
154β
155 expect(mutation().isIdle).toBe(true)
156β
157 const successPromise = mutation.mutateAsync(10)
158 await waitFor(() => mutation().isPending)
159 await expect(successPromise).resolves.toBe(11)
160 await waitFor(() => mutation().isSuccess)
161 expect(mutation().data).toBe(11)
162β
163 const errorPromise = mutation.mutateAsync(-1)
164 await waitFor(() => mutation().isPending)
165 await expect(errorPromise).rejects.toThrow('negative-not-allowed')
166 await waitFor(() => mutation().isError)
167 expect(mutation().error).toBeInstanceOf(Error)
168 })
169β
170 it('M10: reset clears mutation state back to idle baseline', async () => {
171 const client = new QueryClient()
172 const host = new TestControllerHost()
173β
174 const mutation = createMutationController(
175 host,
176 {
177 mutationFn: async () => {
178 throw new Error('reset-target')
179 },
180 },
181 client,
182 )
183β
184 host.connect()
185 host.update()
186β
187 await expect(mutation.mutateAsync(undefined)).rejects.toThrow(
188 'reset-target',
189 )
190 await waitFor(() => mutation().isError)
191 expect(mutation().error).toBeInstanceOf(Error)
192β
193 mutation.reset()
194 expect(mutation().isIdle).toBe(true)
195 expect(mutation().isPaused).toBe(false)
196 expect(mutation().isError).toBe(false)
197 expect(mutation().error).toBeNull()
198 expect(mutation().data).toBeUndefined()
199 })
200β
201 it('M11: mutate is non-throwing while mutateAsync rejects on error', async () => {
202 const client = new QueryClient()
203 const host = new TestControllerHost()
204β
205 const mutation = createMutationController(
206 host,
207 {
208 mutationFn: async (value: number) => {
209 if (value < 0) {
210 throw new Error('negative-not-allowed')
211 }
212β
213 return value + 1
214 },
215 },
216 client,
217 )
218β
219 host.connect()
220 host.update()
221β
222 expect(() => mutation.mutate(-1)).not.toThrow()
223 await waitFor(() => mutation().isError)
224 expect(mutation().error).toBeInstanceOf(Error)
225β
226 await expect(mutation.mutateAsync(-1)).rejects.toThrow(
227 'negative-not-allowed',
228 )
229 })
230β
231 it('M12: mutation callback order and call counts are deterministic', async () => {
232 const client = new QueryClient()
233 const host = new TestControllerHost()
234 const callbackEvents: string[] = []
235β
236 const mutation = createMutationController(
237 host,
238 {
239 mutationFn: async (value: number) => {
240 await new Promise((resolve) => setTimeout(resolve, 5))
241 if (value < 0) {
242 throw new Error('callback-order-failure')
243 }
244 return value + 1
245 },
246 onSuccess: (_data, value) => {
247 callbackEvents.push(`success:${value}`)
248 },
249 onError: (_error, value) => {
250 callbackEvents.push(`error:${value}`)
251 },
252 onSettled: (_data, _error, value) => {
253 callbackEvents.push(`settled:${value}`)
254 },
255 },
256 client,
257 )
258β
259 host.connect()
260 host.update()
261β
262 await expect(mutation.mutateAsync(1)).resolves.toBe(2)
263 await expect(mutation.mutateAsync(-1)).rejects.toThrow(
264 'callback-order-failure',
265 )
266β
267 expect(callbackEvents).toEqual([
268 'success:1',
269 'settled:1',
270 'error:-1',
271 'settled:-1',
272 ])
273 })
274β
275 it('AREACT-02: refreshed mutation callbacks use latest closures', async () => {
276 const client = new QueryClient()
277 const host = new TestControllerHost()
278 const callbackEvents: string[] = []
279 let version = 'v1'
280β
281 const mutation = createMutationController(
282 host,
283 () => ({
284 mutationFn: async (value: number) => {
285 if (value < 0) {
286 throw new Error('freshness-failure')
287 }
288 return value + 1
289 },
290 onSuccess: () => {
291 callbackEvents.push(`success:${version}`)
292 },
293 onError: () => {
294 callbackEvents.push(`error:${version}`)
295 },
296 onSettled: () => {
297 callbackEvents.push(`settled:${version}`)
298 },
299 }),
300 client,
301 )
302β
303 host.connect()
304 host.update()
305β
306 await expect(mutation.mutateAsync(1)).resolves.toBe(2)
307 expect(callbackEvents.slice(0, 2)).toEqual(['success:v1', 'settled:v1'])
308β
309 version = 'v2'
310 host.update()
311β
312 await expect(mutation.mutateAsync(-1)).rejects.toThrow('freshness-failure')
313 expect(callbackEvents.slice(2)).toEqual(['error:v2', 'settled:v2'])
314 })
315β
316 it('LC-MUT-03: missing provider becomes a deterministic missing-client state', async () => {
317 const consumer = document.createElement(
318 contextMutationTagName,
319 ) as ContextMutationHostElement
320 const placeholderResult = consumer.mutation()
321β
322 expect(placeholderResult.isIdle).toBe(true)
323 expect(placeholderResult.isPaused).toBe(false)
324β
325 document.body.append(consumer)
326β
327 expect(() => consumer.mutation()).not.toThrow()
328 await waitForMissingQueryClient(() => consumer.mutation())
329β
330 expect(() => consumer.mutation.mutate(1)).toThrow(
331 /No QueryClient available/,
332 )
333 await expect(consumer.mutation.mutateAsync(1)).rejects.toThrow(
334 /No QueryClient available/,
335 )
336 await expect(placeholderResult.mutate(1)).rejects.toThrow(
337 /No QueryClient available/,
338 )
339β
340 expect(() => consumer.mutation.reset()).not.toThrow()
341 expect(() => placeholderResult.reset()).not.toThrow()
342β
343 consumer.mutation.destroy()
344 consumer.remove()
345 await Promise.resolve()
346 })
347β
348 it('LC-MUT-04: later valid provider adoption recovers without reconstruction', async () => {
349 const consumer = document.createElement(
350 contextMutationTagName,
351 ) as ContextMutationHostElement
352β
353 document.body.append(consumer)
354 await waitForMissingQueryClient(() => consumer.mutation())
355β
356 const client = new QueryClient()
357 const provider = document.createElement(
358 providerTagName,
359 ) as QueryClientProvider
360 provider.client = client
361 provider.append(consumer)
362β
363 document.body.append(provider)
364 await provider.updateComplete
365 await Promise.resolve()
366β
367 await expect(consumer.mutation.mutateAsync(1)).resolves.toBe(2)
368 expect(consumer.mutation().isSuccess).toBe(true)
369β
370 consumer.mutation.destroy()
371 provider.remove()
372 await Promise.resolve()
373 })
374β
375 it('ALREADYCONN-MUT-01: mutation controller on already-connected host with explicit client does not throw', async () => {
376 // Regression test for SSR hydration scenario where controller is created
377 // during willUpdate on an already-connected host.
378 const client = new QueryClient()
379β
380 // Create a host that simulates Lit's behavior: addController calls
381 // hostConnected immediately if the host is already connected
382 class AlreadyConnectedHost {
383 private readonly controllers = new Set<{
384 hostConnected?: () => void
385 }>()
386 private isConnected = true
387 updatesRequested = 0
388 readonly updateComplete: Promise<boolean> = Promise.resolve(true)
389β
390 addController(controller: { hostConnected?: () => void }): void {
391 this.controllers.add(controller)
392 if (this.isConnected) {
393 controller.hostConnected?.()
394 }
395 }
396β
397 removeController(controller: { hostConnected?: () => void }): void {
398 this.controllers.delete(controller)
399 }
400β
401 requestUpdate(): void {
402 this.updatesRequested += 1
403 }
404 }
405β
406 const host = new AlreadyConnectedHost()
407β
408 // This should NOT throw even though hostConnected runs during construction
409 const mutation = createMutationController(
410 host,
411 {
412 mutationKey: ['already-connected-mutation-test'],
413 mutationFn: async (value: number) => value * 2,
414 },
415 client,
416 )
417β
418 // Wait for the deferred onConnected to complete
419 await Promise.resolve()
420 await Promise.resolve()
421β
422 // Mutation controller should work correctly
423 expect(mutation().isIdle).toBe(true)
424 await expect(mutation.mutateAsync(5)).resolves.toBe(10)
425 expect(mutation().isSuccess).toBe(true)
426β
427 mutation.destroy()
428 })
429β
430 it('LC-MUT-05: explicit-client mutation accessors defer until host fields are initialized', () => {
431 const client = new QueryClient()
432β
433 class DeferredExplicitMutationHost implements ReactiveControllerHost {
434 private readonly controllers = new Set<ReactiveController>()
435β
436 updatesRequested = 0
437 readonly updateComplete: Promise<boolean> = Promise.resolve(true)
438β
439 readonly mutation = createMutationController(
440 this,
441 () => ({
442 mutationKey: ['deferred-explicit-mutation', this.id] as const,
443 mutationFn: async (value: number) => value + this.offset,
444 }),
445 client,
446 )
447β
448 readonly firstRead = this.mutation()
449 readonly id = 'alpha'
450 readonly offset = 1
451β
452 addController(controller: ReactiveController): void {
453 this.controllers.add(controller)
454 }
455β
456 removeController(controller: ReactiveController): void {
457 this.controllers.delete(controller)
458 }
459β
460 requestUpdate(): void {
461 this.updatesRequested += 1
462 }
463 }
464β
465 expect(() => new DeferredExplicitMutationHost()).not.toThrow()
466β
467 const host = new DeferredExplicitMutationHost()
468 expect(host.mutation().isIdle).toBe(true)
469β
470 host.mutation.destroy()
471 })
472})