Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import { QueryClient } from '@tanstack/query-core'
3import { queryKey, sleep } from '@tanstack/query-test-utils'
4import { LitElement, html } from 'lit'
5import { QueryClientProvider } from '../QueryClientProvider.js'
6import { createMutationController } from '../createMutationController.js'
7import { useMutationState } from '../useMutationState.js'
8import { generateElementName } from './utils.js'
9import type { MutationStateAccessor } from '../useMutationState.js'
10β
11const providerTagName = generateElementName()
12customElements.define(providerTagName, QueryClientProvider)
13β
14describe('useMutationState', () => {
15 let queryClient: QueryClient
16 let container: HTMLElement
17β
18 beforeEach(() => {
19 vi.useFakeTimers()
20 queryClient = new QueryClient()
21 container = document.createElement('div')
22 document.body.append(container)
23 })
24β
25 afterEach(() => {
26 container.remove()
27 queryClient.clear()
28 vi.useRealTimers()
29 })
30β
31 it('should not request another update when stable mutation state selectors refresh during host update', async () => {
32 class Host extends LitElement {
33 static override properties = { count: { type: Number } }
34β
35 declare count: number
36β
37 updatesRequested = 0
38β
39 readonly mutationStates = useMutationState<string>(
40 this,
41 {
42 select: (mutation) => mutation.state.status,
43 },
44 queryClient,
45 )
46β
47 override requestUpdate(
48 ...args: Parameters<LitElement['requestUpdate']>
49 ): void {
50 this.updatesRequested += 1
51 super.requestUpdate(...args)
52 }
53 }
54 customElements.define(generateElementName(), Host)
55 const host = new Host()
56 const mutationStates = host.mutationStates
57β
58 try {
59 container.append(host)
60 await host.updateComplete
61β
62 await vi.advanceTimersByTimeAsync(0)
63 expect(mutationStates()).toEqual([])
64β
65 host.updatesRequested = 0
66β
67 for (let i = 0; i < 5; i += 1) {
68 host.count = i
69 await host.updateComplete
70 }
71β
72 expect(host.updatesRequested).toBe(5)
73 expect(mutationStates()).toEqual([])
74 } finally {
75 mutationStates.destroy()
76 }
77 })
78β
79 it('should not request another update when mutation cache emits with unchanged selected state', async () => {
80 const mutationKey = queryKey()
81 const mutation = queryClient.getMutationCache().build(queryClient, {
82 mutationKey,
83 })
84β
85 class Host extends LitElement {
86 updatesRequested = 0
87β
88 readonly mutationStates = useMutationState<string>(
89 this,
90 {
91 filters: { mutationKey },
92 select: (mutation) => mutation.state.status,
93 },
94 queryClient,
95 )
96β
97 override requestUpdate(
98 ...args: Parameters<LitElement['requestUpdate']>
99 ): void {
100 this.updatesRequested += 1
101 super.requestUpdate(...args)
102 }
103 }
104 customElements.define(generateElementName(), Host)
105 const host = new Host()
106 const mutationStates = host.mutationStates
107β
108 try {
109 container.append(host)
110 await host.updateComplete
111β
112 await vi.advanceTimersByTimeAsync(0)
113 expect(mutationStates()).toEqual(['idle'])
114β
115 host.updatesRequested = 0
116β
117 for (let i = 0; i < 5; i += 1) {
118 queryClient.getMutationCache().notify({
119 type: 'updated',
120 mutation,
121 action: { type: 'pause' } as never,
122 })
123 await vi.advanceTimersByTimeAsync(0)
124 }
125β
126 expect(host.updatesRequested).toBe(0)
127 expect(mutationStates()).toEqual(['idle'])
128 } finally {
129 mutationStates.destroy()
130 }
131 })
132β
133 it('should keep the pre-connect placeholder empty until a provider binds', async () => {
134 const mutationKey = queryKey()
135β
136 class Consumer extends LitElement {
137 readonly mutationKey = mutationKey
138β
139 readonly mutation = createMutationController(this, {
140 mutationKey: this.mutationKey,
141 mutationFn: () => sleep(10).then(() => 'mutation-ok'),
142 })
143β
144 readonly mutationStatuses = useMutationState<string>(this, {
145 filters: { mutationKey: this.mutationKey },
146 select: (mutation) => mutation.state.status,
147 })
148 }
149 customElements.define(generateElementName(), Consumer)
150 const consumer = new Consumer()
151β
152 expect(consumer.mutationStatuses()).toEqual([])
153β
154 const provider = document.createElement(
155 providerTagName,
156 ) as QueryClientProvider
157 provider.client = queryClient
158 provider.append(consumer)
159β
160 container.append(provider)
161 await provider.updateComplete
162 await consumer.updateComplete
163β
164 consumer.mutation.mutate()
165 await vi.advanceTimersByTimeAsync(10)
166 expect(consumer.mutationStatuses()).toContain('success')
167β
168 consumer.mutation.destroy()
169 consumer.mutationStatuses.destroy()
170 provider.remove()
171 })
172β
173 it('should prefer an explicit client over the provider context', async () => {
174 const mutationKey = queryKey()
175 const providerClient = new QueryClient()
176β
177 const provider = document.createElement(
178 providerTagName,
179 ) as QueryClientProvider
180 provider.client = providerClient
181β
182 class Consumer extends LitElement {
183 readonly mutationKey = mutationKey
184β
185 readonly mutation = createMutationController(
186 this,
187 {
188 mutationKey: this.mutationKey,
189 mutationFn: () => sleep(10).then(() => 'mutation-ok'),
190 },
191 queryClient,
192 )
193β
194 readonly mutationStatuses = useMutationState<string>(
195 this,
196 {
197 filters: { mutationKey: this.mutationKey },
198 select: (mutation) => mutation.state.status,
199 },
200 queryClient,
201 )
202 }
203 customElements.define(generateElementName(), Consumer)
204 const consumer = new Consumer()
205 provider.append(consumer)
206β
207 container.append(provider)
208 await provider.updateComplete
209 await consumer.updateComplete
210β
211 consumer.mutation.mutate()
212 await vi.advanceTimersByTimeAsync(10)
213 expect(consumer.mutationStatuses()).toEqual(['success'])
214β
215 consumer.mutation.destroy()
216 consumer.mutationStatuses.destroy()
217 provider.remove()
218 })
219β
220 it('should track mutation state', async () => {
221 class Producer extends LitElement {
222 readonly mutation = createMutationController(
223 this,
224 {
225 mutationFn: (value: number) => sleep(10).then(() => value + 10),
226 },
227 queryClient,
228 )
229 }
230 customElements.define(generateElementName(), Producer)
231β
232 class Host extends LitElement {
233 readonly mutationStatuses = useMutationState<string>(
234 this,
235 {
236 select: (item) => item.state.status,
237 },
238 queryClient,
239 )
240β
241 override render() {
242 const statuses = this.mutationStatuses().join(', ') || 'none'
243 return html`<p>statuses: ${statuses}</p>`
244 }
245 }
246 customElements.define(generateElementName(), Host)
247 const producer = new Producer()
248 const host = new Host()
249 container.append(producer, host)
250 const { mutation } = producer
251 const { mutationStatuses } = host
252β
253 mutation.mutate(1)
254 await vi.advanceTimersByTimeAsync(0)
255 expect(host.shadowRoot).toHaveTextContent('statuses: pending')
256 await vi.advanceTimersByTimeAsync(10)
257 expect(mutationStatuses()).toContain('success')
258 expect(host.shadowRoot).toHaveTextContent('statuses: success')
259 })
260β
261 it('should not process mutation cache updates while disconnected', async () => {
262 class Producer extends LitElement {
263 readonly mutation = createMutationController(
264 this,
265 {
266 mutationFn: (value: number) => sleep(10).then(() => value + 10),
267 },
268 queryClient,
269 )
270 }
271 customElements.define(generateElementName(), Producer)
272β
273 class Host extends LitElement {
274 updatesRequested = 0
275β
276 readonly mutationStatuses = useMutationState<string>(
277 this,
278 {
279 select: (item) => item.state.status,
280 },
281 queryClient,
282 )
283β
284 override requestUpdate(
285 ...args: Parameters<LitElement['requestUpdate']>
286 ): void {
287 this.updatesRequested += 1
288 super.requestUpdate(...args)
289 }
290 }
291 customElements.define(generateElementName(), Host)
292 const producer = new Producer()
293 const host = new Host()
294 container.append(producer, host)
295 const { mutation } = producer
296 await host.updateComplete
297β
298 host.remove()
299 await host.updateComplete
300 const updatesAfterDisconnect = host.updatesRequested
301β
302 mutation.mutate(1)
303 await vi.advanceTimersByTimeAsync(10)
304 expect(host.updatesRequested).toBe(updatesAfterDisconnect)
305 })
306β
307 it('should return the states of all mutations when options are omitted', async () => {
308 class Producer extends LitElement {
309 readonly mutation1 = createMutationController(this, {
310 mutationKey: queryKey(),
311 mutationFn: () => sleep(10).then(() => 'data1'),
312 })
313β
314 readonly mutation2 = createMutationController(this, {
315 mutationKey: queryKey(),
316 mutationFn: () => sleep(10).then(() => 'data2'),
317 })
318 }
319 customElements.define(generateElementName(), Producer)
320β
321 class Host extends LitElement {
322 readonly mutationStates = useMutationState(this)
323β
324 override render() {
325 const statuses = this.mutationStates()
326 .map((state) => state.status)
327 .join(', ')
328 return html`<p>statuses: ${statuses || 'none'}</p>`
329 }
330 }
331 customElements.define(generateElementName(), Host)
332 const provider = document.createElement(
333 providerTagName,
334 ) as QueryClientProvider
335 provider.client = queryClient
336 const producer = new Producer()
337 const host = new Host()
338 provider.append(producer, host)
339β
340 container.append(provider)
341 await provider.updateComplete
342β
343 expect(host.shadowRoot).toHaveTextContent('statuses: none')
344β
345 producer.mutation1.mutate()
346 producer.mutation2.mutate()
347 await vi.advanceTimersByTimeAsync(0)
348 expect(host.shadowRoot).toHaveTextContent('statuses: pending, pending')
349 await vi.advanceTimersByTimeAsync(10)
350 expect(host.shadowRoot).toHaveTextContent('statuses: success, success')
351 })
352β
353 it('should select and filter by mutation key/status in useMutationState', async () => {
354 const mutationKey1 = queryKey()
355 const mutationKey2 = queryKey()
356 let activeFilter: { mutationKey?: ReadonlyArray<string> } = {
357 mutationKey: mutationKey1,
358 }
359β
360 class Host extends LitElement {
361 readonly mutationA = createMutationController(
362 this,
363 {
364 mutationKey: mutationKey1,
365 mutationFn: () => sleep(10).then(() => 'ok'),
366 },
367 queryClient,
368 )
369β
370 readonly mutationB = createMutationController(
371 this,
372 {
373 mutationKey: mutationKey2,
374 mutationFn: () =>
375 sleep(10).then(() => Promise.reject(new Error('state-b-failure'))),
376 },
377 queryClient,
378 )
379β
380 readonly mutationStatuses = useMutationState<string>(
381 this,
382 {
383 filters: () => activeFilter,
384 select: (item) => item.state.status,
385 },
386 queryClient,
387 )
388β
389 override render() {
390 const statuses = this.mutationStatuses().join(', ') || 'none'
391 return html`<p>statuses: ${statuses}</p>`
392 }
393 }
394 customElements.define(generateElementName(), Host)
395 const host = new Host()
396 container.append(host)
397 const { mutationA, mutationB, mutationStatuses } = host
398β
399 const promiseA = mutationA.mutateAsync(undefined)
400 await vi.advanceTimersByTimeAsync(10)
401 await expect(promiseA).resolves.toBe('ok')
402 await Promise.all([
403 expect(mutationB.mutateAsync(undefined)).rejects.toThrow(
404 'state-b-failure',
405 ),
406 vi.advanceTimersByTimeAsync(10),
407 ])
408 expect(mutationStatuses()).toEqual(['success'])
409 expect(host.shadowRoot).toHaveTextContent('statuses: success')
410β
411 activeFilter = { mutationKey: mutationKey2 }
412 host.requestUpdate()
413 await host.updateComplete
414β
415 expect(mutationStatuses()).toEqual(['error'])
416 expect(host.shadowRoot).toHaveTextContent('statuses: error')
417 })
418β
419 it('should refresh useMutationState when the select closure changes on host update', async () => {
420 const mutationKey = queryKey()
421 let label = 'before'
422β
423 class Host extends LitElement {
424 readonly mutation = createMutationController(
425 this,
426 {
427 mutationKey,
428 mutationFn: () => sleep(10).then(() => 'ok'),
429 },
430 queryClient,
431 )
432β
433 readonly mutationLabels = useMutationState<string>(
434 this,
435 {
436 filters: {
437 mutationKey,
438 },
439 select: () => label,
440 },
441 queryClient,
442 )
443β
444 override render() {
445 const labels = this.mutationLabels().join(', ') || 'none'
446 return html`<p>labels: ${labels}</p>`
447 }
448 }
449 customElements.define(generateElementName(), Host)
450 const host = new Host()
451 container.append(host)
452 const { mutation, mutationLabels } = host
453β
454 const promise = mutation.mutateAsync(undefined)
455 await vi.advanceTimersByTimeAsync(10)
456 await expect(promise).resolves.toBe('ok')
457 expect(mutationLabels()).toEqual(['before'])
458 expect(host.shadowRoot).toHaveTextContent('labels: before')
459β
460 label = 'after'
461 host.requestUpdate()
462 await host.updateComplete
463β
464 expect(mutationLabels()).toEqual(['after'])
465 expect(host.shadowRoot).toHaveTextContent('labels: after')
466β
467 mutation.destroy()
468 mutationLabels.destroy()
469 })
470β
471 it('should fail after the handshake and recover under a provider', async () => {
472 const mutationKey = queryKey()
473β
474 class Consumer extends LitElement {
475 readonly mutationKey = mutationKey
476β
477 readonly mutationStatuses = useMutationState<string>(this, {
478 filters: { mutationKey: this.mutationKey },
479 select: (mutation) => mutation.state.status,
480 })
481 }
482 customElements.define(generateElementName(), Consumer)
483 const consumer = new Consumer()
484β
485 expect(consumer.mutationStatuses()).toEqual([])
486β
487 container.append(consumer)
488β
489 await vi.advanceTimersByTimeAsync(0)
490 expect(() => consumer.mutationStatuses()).toThrow(
491 /No QueryClient available/,
492 )
493β
494 const provider = document.createElement(
495 providerTagName,
496 ) as QueryClientProvider
497 provider.client = queryClient
498 provider.append(consumer)
499β
500 container.append(provider)
501 await provider.updateComplete
502 await consumer.updateComplete
503β
504 expect(consumer.mutationStatuses()).toEqual([])
505β
506 consumer.mutationStatuses.destroy()
507 provider.remove()
508 })
509β
510 it('should not throw on an already-connected host with an explicit client', async () => {
511 const mutationKey = queryKey()
512β
513 class Producer extends LitElement {
514 readonly mutation = createMutationController(
515 this,
516 {
517 mutationKey,
518 mutationFn: () => sleep(10).then(() => 'mutation-ok'),
519 },
520 queryClient,
521 )
522 }
523 customElements.define(generateElementName(), Producer)
524 const producer = new Producer()
525 container.append(producer)
526 const producerMutation = producer.mutation
527β
528 producerMutation.mutate()
529β
530 class Host extends LitElement {
531 mutationStatuses?: MutationStateAccessor<string>
532 }
533 customElements.define(generateElementName(), Host)
534 const host = new Host()
535 container.append(host)
536 await host.updateComplete
537β
538 // Lit calls hostConnected immediately when a controller is added to an
539 // already-connected host
540 host.mutationStatuses = useMutationState<string>(
541 host,
542 {
543 filters: { mutationKey },
544 select: (mutation) => mutation.state.status,
545 },
546 queryClient,
547 )
548 const { mutationStatuses } = host
549β
550 expect(mutationStatuses()).toContain('pending')
551 await vi.advanceTimersByTimeAsync(10)
552 expect(mutationStatuses()).toContain('success')
553β
554 mutationStatuses.destroy()
555 producerMutation.destroy()
556 })
557})