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β
55 customElements.define(generateElementName(), Host)
56 const host = new Host()
57 const mutationStates = host.mutationStates
58β
59 try {
60 container.append(host)
61 await host.updateComplete
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 expect(host.updatesRequested).toBe(5)
72 expect(mutationStates()).toEqual([])
73 } finally {
74 mutationStates.destroy()
75 }
76 })
77β
78 it('should not request another update when mutation cache emits with unchanged selected state', async () => {
79 const mutationKey = queryKey()
80 const mutation = queryClient.getMutationCache().build(queryClient, {
81 mutationKey,
82 })
83β
84 class Host extends LitElement {
85 updatesRequested = 0
86β
87 readonly mutationStates = useMutationState<string>(
88 this,
89 {
90 filters: { mutationKey },
91 select: (mutation) => mutation.state.status,
92 },
93 queryClient,
94 )
95β
96 override requestUpdate(
97 ...args: Parameters<LitElement['requestUpdate']>
98 ): void {
99 this.updatesRequested += 1
100 super.requestUpdate(...args)
101 }
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 await vi.advanceTimersByTimeAsync(0)
112 expect(mutationStates()).toEqual(['idle'])
113β
114 host.updatesRequested = 0
115β
116 for (let i = 0; i < 5; i += 1) {
117 queryClient.getMutationCache().notify({
118 type: 'updated',
119 mutation,
120 action: { type: 'pause' } as never,
121 })
122 await vi.advanceTimersByTimeAsync(0)
123 }
124 expect(host.updatesRequested).toBe(0)
125 expect(mutationStates()).toEqual(['idle'])
126 } finally {
127 mutationStates.destroy()
128 }
129 })
130β
131 it('should keep the pre-connect placeholder empty until a provider binds', async () => {
132 const mutationKey = queryKey()
133β
134 class Consumer extends LitElement {
135 readonly mutationKey = mutationKey
136β
137 readonly mutation = createMutationController(this, {
138 mutationKey: this.mutationKey,
139 mutationFn: () => sleep(10).then(() => 'mutation-ok'),
140 })
141β
142 readonly mutationStatuses = useMutationState<string>(this, {
143 filters: { mutationKey: this.mutationKey },
144 select: (mutation) => mutation.state.status,
145 })
146 }
147β
148 customElements.define(generateElementName(), Consumer)
149 const consumer = new Consumer()
150β
151 expect(consumer.mutationStatuses()).toEqual([])
152β
153 const provider = document.createElement(
154 providerTagName,
155 ) as QueryClientProvider
156 provider.client = queryClient
157 provider.append(consumer)
158 container.append(provider)
159 await provider.updateComplete
160 await consumer.updateComplete
161β
162 consumer.mutation.mutate()
163 await vi.advanceTimersByTimeAsync(10)
164 expect(consumer.mutationStatuses()).toContain('success')
165β
166 consumer.mutation.destroy()
167 consumer.mutationStatuses.destroy()
168 provider.remove()
169 })
170β
171 it('should prefer an explicit client over the provider context', async () => {
172 const mutationKey = queryKey()
173 const providerClient = new QueryClient()
174β
175 const provider = document.createElement(
176 providerTagName,
177 ) as QueryClientProvider
178 provider.client = providerClient
179β
180 class Consumer extends LitElement {
181 readonly mutationKey = mutationKey
182β
183 readonly mutation = createMutationController(
184 this,
185 {
186 mutationKey: this.mutationKey,
187 mutationFn: () => sleep(10).then(() => 'mutation-ok'),
188 },
189 queryClient,
190 )
191β
192 readonly mutationStatuses = useMutationState<string>(
193 this,
194 {
195 filters: { mutationKey: this.mutationKey },
196 select: (mutation) => mutation.state.status,
197 },
198 queryClient,
199 )
200 }
201β
202 customElements.define(generateElementName(), Consumer)
203 const consumer = new Consumer()
204 provider.append(consumer)
205 container.append(provider)
206 await provider.updateComplete
207 await consumer.updateComplete
208β
209 consumer.mutation.mutate()
210 await vi.advanceTimersByTimeAsync(10)
211 expect(consumer.mutationStatuses()).toEqual(['success'])
212β
213 consumer.mutation.destroy()
214 consumer.mutationStatuses.destroy()
215 provider.remove()
216 })
217β
218 it('should track mutation state', async () => {
219 class Producer extends LitElement {
220 readonly mutation = createMutationController(
221 this,
222 {
223 mutationFn: (value: number) => sleep(10).then(() => value + 10),
224 },
225 queryClient,
226 )
227 }
228β
229 customElements.define(generateElementName(), Producer)
230β
231 class Host extends LitElement {
232 readonly mutationStatuses = useMutationState<string>(
233 this,
234 {
235 select: (item) => item.state.status,
236 },
237 queryClient,
238 )
239β
240 override render() {
241 const statuses = this.mutationStatuses().join(', ') || 'none'
242 return html`<p>statuses: ${statuses}</p>`
243 }
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 return the current mutation states when connected after a mutation started', 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β
272 customElements.define(generateElementName(), Producer)
273β
274 class Host extends LitElement {
275 readonly mutationStates = useMutationState(
276 this,
277 {
278 filters: { status: 'pending' },
279 },
280 queryClient,
281 )
282β
283 override render() {
284 return html`<p>pending: ${this.mutationStates().length}</p>`
285 }
286 }
287β
288 customElements.define(generateElementName(), Host)
289 const producer = new Producer()
290 const host = new Host()
291 container.append(producer)
292 const { mutation } = producer
293 await producer.updateComplete
294β
295 mutation.mutate(1)
296 container.append(host)
297 await vi.advanceTimersByTimeAsync(0)
298 expect(host.shadowRoot).toHaveTextContent('pending: 1')
299 await vi.advanceTimersByTimeAsync(10)
300 expect(host.shadowRoot).toHaveTextContent('pending: 0')
301 })
302β
303 it('should not process mutation cache updates while disconnected', async () => {
304 class Producer extends LitElement {
305 readonly mutation = createMutationController(
306 this,
307 {
308 mutationFn: (value: number) => sleep(10).then(() => value + 10),
309 },
310 queryClient,
311 )
312 }
313β
314 customElements.define(generateElementName(), Producer)
315β
316 class Host extends LitElement {
317 updatesRequested = 0
318β
319 readonly mutationStatuses = useMutationState<string>(
320 this,
321 {
322 select: (item) => item.state.status,
323 },
324 queryClient,
325 )
326β
327 override requestUpdate(
328 ...args: Parameters<LitElement['requestUpdate']>
329 ): void {
330 this.updatesRequested += 1
331 super.requestUpdate(...args)
332 }
333 }
334β
335 customElements.define(generateElementName(), Host)
336 const producer = new Producer()
337 const host = new Host()
338 container.append(producer, host)
339 const { mutation } = producer
340 await host.updateComplete
341β
342 host.remove()
343 await host.updateComplete
344 const updatesAfterDisconnect = host.updatesRequested
345β
346 mutation.mutate(1)
347 await vi.advanceTimersByTimeAsync(10)
348 expect(host.updatesRequested).toBe(updatesAfterDisconnect)
349 })
350β
351 it('should return the states of all mutations when options are omitted', async () => {
352 class Producer extends LitElement {
353 readonly mutation1 = createMutationController(this, {
354 mutationKey: queryKey(),
355 mutationFn: () => sleep(10).then(() => 'data1'),
356 })
357β
358 readonly mutation2 = createMutationController(this, {
359 mutationKey: queryKey(),
360 mutationFn: () => sleep(10).then(() => 'data2'),
361 })
362 }
363β
364 customElements.define(generateElementName(), Producer)
365β
366 class Host extends LitElement {
367 readonly mutationStates = useMutationState(this)
368β
369 override render() {
370 const statuses = this.mutationStates()
371 .map((state) => state.status)
372 .join(', ')
373 return html`<p>statuses: ${statuses || 'none'}</p>`
374 }
375 }
376β
377 customElements.define(generateElementName(), Host)
378 const provider = document.createElement(
379 providerTagName,
380 ) as QueryClientProvider
381 provider.client = queryClient
382 const producer = new Producer()
383 const host = new Host()
384 provider.append(producer, host)
385 container.append(provider)
386 await provider.updateComplete
387β
388 expect(host.shadowRoot).toHaveTextContent('statuses: none')
389β
390 producer.mutation1.mutate()
391 producer.mutation2.mutate()
392 await vi.advanceTimersByTimeAsync(0)
393 expect(host.shadowRoot).toHaveTextContent('statuses: pending, pending')
394 await vi.advanceTimersByTimeAsync(10)
395 expect(host.shadowRoot).toHaveTextContent('statuses: success, success')
396 })
397β
398 it('should select and filter by mutation key/status in useMutationState', async () => {
399 const mutationKey1 = queryKey()
400 const mutationKey2 = queryKey()
401 let activeFilter: { mutationKey?: ReadonlyArray<string> } = {
402 mutationKey: mutationKey1,
403 }
404β
405 class Host extends LitElement {
406 readonly mutationA = createMutationController(
407 this,
408 {
409 mutationKey: mutationKey1,
410 mutationFn: () => sleep(10).then(() => 'ok'),
411 },
412 queryClient,
413 )
414β
415 readonly mutationB = createMutationController(
416 this,
417 {
418 mutationKey: mutationKey2,
419 mutationFn: () =>
420 sleep(10).then(() => Promise.reject(new Error('state-b-failure'))),
421 },
422 queryClient,
423 )
424β
425 readonly mutationStatuses = useMutationState<string>(
426 this,
427 {
428 filters: () => activeFilter,
429 select: (item) => item.state.status,
430 },
431 queryClient,
432 )
433β
434 override render() {
435 const statuses = this.mutationStatuses().join(', ') || 'none'
436 return html`<p>statuses: ${statuses}</p>`
437 }
438 }
439β
440 customElements.define(generateElementName(), Host)
441 const host = new Host()
442 container.append(host)
443 const { mutationA, mutationB, mutationStatuses } = host
444β
445 const promiseA = mutationA.mutateAsync(undefined)
446 await vi.advanceTimersByTimeAsync(10)
447 await expect(promiseA).resolves.toBe('ok')
448β
449 await Promise.all([
450 expect(mutationB.mutateAsync(undefined)).rejects.toThrow(
451 'state-b-failure',
452 ),
453 vi.advanceTimersByTimeAsync(10),
454 ])
455 expect(mutationStatuses()).toEqual(['success'])
456 expect(host.shadowRoot).toHaveTextContent('statuses: success')
457β
458 activeFilter = { mutationKey: mutationKey2 }
459 host.requestUpdate()
460 await host.updateComplete
461 expect(mutationStatuses()).toEqual(['error'])
462 expect(host.shadowRoot).toHaveTextContent('statuses: error')
463 })
464β
465 it('should refresh useMutationState when the select closure changes on host update', async () => {
466 const mutationKey = queryKey()
467 let label = 'before'
468β
469 class Host extends LitElement {
470 readonly mutation = createMutationController(
471 this,
472 {
473 mutationKey,
474 mutationFn: () => sleep(10).then(() => 'ok'),
475 },
476 queryClient,
477 )
478β
479 readonly mutationLabels = useMutationState<string>(
480 this,
481 {
482 filters: {
483 mutationKey,
484 },
485 select: () => label,
486 },
487 queryClient,
488 )
489β
490 override render() {
491 const labels = this.mutationLabels().join(', ') || 'none'
492 return html`<p>labels: ${labels}</p>`
493 }
494 }
495β
496 customElements.define(generateElementName(), Host)
497 const host = new Host()
498 container.append(host)
499 const { mutation, mutationLabels } = host
500β
501 const promise = mutation.mutateAsync(undefined)
502 await vi.advanceTimersByTimeAsync(10)
503 await expect(promise).resolves.toBe('ok')
504 expect(mutationLabels()).toEqual(['before'])
505 expect(host.shadowRoot).toHaveTextContent('labels: before')
506β
507 label = 'after'
508 host.requestUpdate()
509 await host.updateComplete
510 expect(mutationLabels()).toEqual(['after'])
511 expect(host.shadowRoot).toHaveTextContent('labels: after')
512β
513 mutation.destroy()
514 mutationLabels.destroy()
515 })
516β
517 it('should fail after the handshake and recover under a provider', async () => {
518 const mutationKey = queryKey()
519β
520 class Consumer extends LitElement {
521 readonly mutationKey = mutationKey
522β
523 readonly mutationStatuses = useMutationState<string>(this, {
524 filters: { mutationKey: this.mutationKey },
525 select: (mutation) => mutation.state.status,
526 })
527 }
528β
529 customElements.define(generateElementName(), Consumer)
530 const consumer = new Consumer()
531β
532 expect(consumer.mutationStatuses()).toEqual([])
533β
534 container.append(consumer)
535 await vi.advanceTimersByTimeAsync(0)
536 expect(() => consumer.mutationStatuses()).toThrow(
537 /No QueryClient available/,
538 )
539β
540 const provider = document.createElement(
541 providerTagName,
542 ) as QueryClientProvider
543 provider.client = queryClient
544 provider.append(consumer)
545 container.append(provider)
546 await provider.updateComplete
547 await consumer.updateComplete
548β
549 expect(consumer.mutationStatuses()).toEqual([])
550β
551 consumer.mutationStatuses.destroy()
552 provider.remove()
553 })
554β
555 it('should not throw on an already-connected host with an explicit client', async () => {
556 const mutationKey = queryKey()
557β
558 class Producer extends LitElement {
559 readonly mutation = createMutationController(
560 this,
561 {
562 mutationKey,
563 mutationFn: () => sleep(10).then(() => 'mutation-ok'),
564 },
565 queryClient,
566 )
567 }
568β
569 customElements.define(generateElementName(), Producer)
570 const producer = new Producer()
571 container.append(producer)
572 const producerMutation = producer.mutation
573β
574 producerMutation.mutate()
575β
576 class Host extends LitElement {
577 mutationStatuses?: MutationStateAccessor<string>
578 }
579β
580 customElements.define(generateElementName(), Host)
581 const host = new Host()
582 container.append(host)
583 await host.updateComplete
584β
585 // Lit calls hostConnected immediately when a controller is added to an
586 // already-connected host
587 host.mutationStatuses = useMutationState<string>(
588 host,
589 {
590 filters: { mutationKey },
591 select: (mutation) => mutation.state.status,
592 },
593 queryClient,
594 )
595 const { mutationStatuses } = host
596 expect(mutationStatuses()).toContain('pending')
597 await vi.advanceTimersByTimeAsync(10)
598 expect(mutationStatuses()).toContain('success')
599β
600 mutationStatuses.destroy()
601 producerMutation.destroy()
602 })
603})