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

useMutationState.test.ts

614 lines17.0 KB

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