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