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

useIsFetching.test.ts

466 lines13.4 KB

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 { createQueryController } from '../createQueryController.js'
7import { useIsFetching } from '../useIsFetching.js'
8import { generateElementName } from './utils.js'
9import type { IsFetchingAccessor } from '../useIsFetching.js'
10​
11const providerTagName = generateElementName()
12customElements.define(providerTagName, QueryClientProvider)
13​
14describe('useIsFetching', () => {
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 keep the pre-connect placeholder zero until a provider binds', async () => {
32 const key = queryKey()
33​
34 class Consumer extends LitElement {
35 readonly queryKey = key
36​
37 readonly query = createQueryController(this, {
38 queryKey: this.queryKey,
39 queryFn: () => sleep(10).then(() => 'query-ok'),
40 retry: false,
41 })
42​
43 readonly isFetching = useIsFetching(this, { queryKey: this.queryKey })
44​
45 override render() {
46 return html`<p>fetching: ${this.isFetching()}</p>`
47 }
48 }
49 customElements.define(generateElementName(), Consumer)
50 const consumer = new Consumer()
51​
52 expect(consumer.query().status).toBe('pending')
53 expect(consumer.isFetching()).toBe(0)
54​
55 const provider = document.createElement(
56 providerTagName,
57 ) as QueryClientProvider
58 provider.client = queryClient
59 provider.append(consumer)
60​
61 container.append(provider)
62 await provider.updateComplete
63 await consumer.updateComplete
64​
65 expect(consumer.isFetching()).toBe(1)
66 await vi.advanceTimersByTimeAsync(0)
67 expect(consumer.shadowRoot).toHaveTextContent('fetching: 1')
68 await vi.advanceTimersByTimeAsync(10)
69 expect(consumer.query().isSuccess).toBe(true)
70 expect(consumer.isFetching()).toBe(0)
71 expect(consumer.shadowRoot).toHaveTextContent('fetching: 0')
72​
73 consumer.query.destroy()
74 consumer.isFetching.destroy()
75 provider.remove()
76 })
77​
78 it('should prefer an explicit client over the provider context', async () => {
79 const key = queryKey()
80 const providerClient = new QueryClient()
81​
82 const provider = document.createElement(
83 providerTagName,
84 ) as QueryClientProvider
85 provider.client = providerClient
86​
87 class Consumer extends LitElement {
88 readonly queryKey = key
89​
90 readonly query = createQueryController(
91 this,
92 {
93 queryKey: this.queryKey,
94 queryFn: () => sleep(10).then(() => 'query-ok'),
95 retry: false,
96 },
97 queryClient,
98 )
99​
100 readonly isFetching = useIsFetching(
101 this,
102 { queryKey: this.queryKey },
103 queryClient,
104 )
105​
106 override render() {
107 return html`<p>fetching: ${this.isFetching()}</p>`
108 }
109 }
110 customElements.define(generateElementName(), Consumer)
111 const consumer = new Consumer()
112 provider.append(consumer)
113​
114 container.append(provider)
115 await provider.updateComplete
116 await consumer.updateComplete
117​
118 expect(consumer.isFetching()).toBe(1)
119 await vi.advanceTimersByTimeAsync(0)
120 expect(consumer.shadowRoot).toHaveTextContent('fetching: 1')
121 await vi.advanceTimersByTimeAsync(10)
122 expect(consumer.query().isSuccess).toBe(true)
123 expect(consumer.shadowRoot).toHaveTextContent('fetching: 0')
124 expect(
125 queryClient.getQueryCache().find({ queryKey: consumer.queryKey })?.state
126 .data,
127 ).toBe('query-ok')
128 expect(
129 providerClient.getQueryCache().find({ queryKey: consumer.queryKey }),
130 ).toBeUndefined()
131​
132 consumer.query.destroy()
133 consumer.isFetching.destroy()
134 provider.remove()
135 })
136​
137 it('should track the fetching count', async () => {
138 const key = queryKey()
139​
140 class Producer extends LitElement {
141 readonly query = createQueryController(
142 this,
143 {
144 queryKey: key,
145 queryFn: () => sleep(10).then(() => 'done'),
146 },
147 queryClient,
148 )
149 }
150 customElements.define(generateElementName(), Producer)
151​
152 class Host extends LitElement {
153 readonly isFetching = useIsFetching(this, {}, queryClient)
154​
155 override render() {
156 return html`<p>fetching: ${this.isFetching()}</p>`
157 }
158 }
159 customElements.define(generateElementName(), Host)
160 const producer = new Producer()
161 const host = new Host()
162 container.append(producer, host)
163 const { query } = producer
164 const { isFetching } = host
165​
166 await vi.advanceTimersByTimeAsync(0)
167 expect(isFetching()).toBe(1)
168 expect(host.shadowRoot).toHaveTextContent('fetching: 1')
169 await vi.advanceTimersByTimeAsync(10)
170 expect(query().isSuccess).toBe(true)
171 expect(isFetching()).toBe(0)
172 expect(host.shadowRoot).toHaveTextContent('fetching: 0')
173 })
174​
175 it('should not process query cache updates while disconnected', async () => {
176 const key = queryKey()
177​
178 class Producer extends LitElement {
179 readonly query = createQueryController(
180 this,
181 {
182 queryKey: key,
183 queryFn: () => sleep(10).then(() => 'data'),
184 },
185 queryClient,
186 )
187 }
188 customElements.define(generateElementName(), Producer)
189​
190 class Host extends LitElement {
191 updatesRequested = 0
192​
193 readonly isFetching = useIsFetching(this, {}, queryClient)
194​
195 override requestUpdate(
196 ...args: Parameters<LitElement['requestUpdate']>
197 ): void {
198 this.updatesRequested += 1
199 super.requestUpdate(...args)
200 }
201 }
202 customElements.define(generateElementName(), Host)
203 const host = new Host()
204 container.append(host)
205 await host.updateComplete
206​
207 host.remove()
208 await host.updateComplete
209 const updatesAfterDisconnect = host.updatesRequested
210​
211 container.append(new Producer())
212​
213 await vi.advanceTimersByTimeAsync(10)
214 expect(host.updatesRequested).toBe(updatesAfterDisconnect)
215 })
216​
217 it('should count all fetching queries when filters are omitted', async () => {
218 const key1 = queryKey()
219 const key2 = queryKey()
220​
221 class Producer extends LitElement {
222 readonly query1 = createQueryController(this, {
223 queryKey: key1,
224 queryFn: () => sleep(10).then(() => 'data1'),
225 })
226​
227 readonly query2 = createQueryController(this, {
228 queryKey: key2,
229 queryFn: () => sleep(10).then(() => 'data2'),
230 })
231 }
232 customElements.define(generateElementName(), Producer)
233​
234 class Host extends LitElement {
235 readonly isFetching = useIsFetching(this)
236​
237 override render() {
238 return html`<p>fetching: ${this.isFetching()}</p>`
239 }
240 }
241 customElements.define(generateElementName(), Host)
242 const provider = document.createElement(
243 providerTagName,
244 ) as QueryClientProvider
245 provider.client = queryClient
246 const producer = new Producer()
247 const host = new Host()
248 provider.append(producer, host)
249​
250 container.append(provider)
251 await provider.updateComplete
252 await vi.advanceTimersByTimeAsync(0)
253 expect(host.shadowRoot).toHaveTextContent('fetching: 2')
254 await vi.advanceTimersByTimeAsync(10)
255 expect(host.shadowRoot).toHaveTextContent('fetching: 0')
256 })
257​
258 it('should be able to filter', async () => {
259 const key1 = queryKey()
260 const key2 = queryKey()
261​
262 class Host extends LitElement {
263 readonly query1 = createQueryController(
264 this,
265 {
266 queryKey: key1,
267 queryFn: () => sleep(10).then(() => 'a'),
268 },
269 queryClient,
270 )
271​
272 readonly query2 = createQueryController(
273 this,
274 {
275 queryKey: key2,
276 queryFn: () => sleep(20).then(() => 'b'),
277 },
278 queryClient,
279 )
280​
281 readonly isFetchingAll = useIsFetching(this, {}, queryClient)
282 readonly isFetchingFiltered = useIsFetching(
283 this,
284 { queryKey: key1 },
285 queryClient,
286 )
287​
288 override render() {
289 const all = this.isFetchingAll()
290 const filtered = this.isFetchingFiltered()
291 return html`<p>all: ${all}, filtered: ${filtered}</p>`
292 }
293 }
294 customElements.define(generateElementName(), Host)
295 const host = new Host()
296 container.append(host)
297 const { isFetchingAll, isFetchingFiltered } = host
298​
299 await vi.advanceTimersByTimeAsync(0)
300 expect(isFetchingAll()).toBe(2)
301 expect(isFetchingFiltered()).toBe(1)
302 expect(host.shadowRoot).toHaveTextContent('all: 2, filtered: 1')
303 await vi.advanceTimersByTimeAsync(10)
304 expect(isFetchingAll()).toBe(1)
305 expect(isFetchingFiltered()).toBe(0)
306 expect(host.shadowRoot).toHaveTextContent('all: 1, filtered: 0')
307 await vi.advanceTimersByTimeAsync(10)
308 expect(isFetchingAll()).toBe(0)
309 expect(isFetchingFiltered()).toBe(0)
310 expect(host.shadowRoot).toHaveTextContent('all: 0, filtered: 0')
311 })
312​
313 it('should apply updated filters on host updates', async () => {
314 const key1 = queryKey()
315 const key2 = queryKey()
316 const unmatchedKey = queryKey()
317 let activeFilter: { queryKey?: ReadonlyArray<string> } = {
318 queryKey: key1,
319 }
320​
321 class Host extends LitElement {
322 readonly query1 = createQueryController(
323 this,
324 {
325 queryKey: key1,
326 queryFn: () => sleep(10).then(() => 'a'),
327 },
328 queryClient,
329 )
330​
331 readonly query2 = createQueryController(
332 this,
333 {
334 queryKey: key2,
335 queryFn: () => sleep(20).then(() => 'b'),
336 },
337 queryClient,
338 )
339​
340 readonly isFetchingFiltered = useIsFetching(
341 this,
342 () => activeFilter,
343 queryClient,
344 )
345​
346 override render() {
347 return html`<p>filtered: ${this.isFetchingFiltered()}</p>`
348 }
349 }
350 customElements.define(generateElementName(), Host)
351 const host = new Host()
352 container.append(host)
353 const { isFetchingFiltered } = host
354​
355 await vi.advanceTimersByTimeAsync(0)
356 expect(isFetchingFiltered()).toBe(1)
357 expect(host.shadowRoot).toHaveTextContent('filtered: 1')
358​
359 activeFilter = { queryKey: unmatchedKey }
360 host.requestUpdate()
361 await host.updateComplete
362​
363 expect(isFetchingFiltered()).toBe(0)
364 expect(host.shadowRoot).toHaveTextContent('filtered: 0')
365​
366 activeFilter = { queryKey: key2 }
367 host.requestUpdate()
368 await host.updateComplete
369​
370 expect(isFetchingFiltered()).toBe(1)
371 expect(host.shadowRoot).toHaveTextContent('filtered: 1')
372 await vi.advanceTimersByTimeAsync(10)
373 expect(isFetchingFiltered()).toBe(1)
374 expect(host.shadowRoot).toHaveTextContent('filtered: 1')
375 await vi.advanceTimersByTimeAsync(10)
376 expect(isFetchingFiltered()).toBe(0)
377 expect(host.shadowRoot).toHaveTextContent('filtered: 0')
378 })
379​
380 it('should fail after the handshake and recover under a provider', async () => {
381 const key = queryKey()
382​
383 class Consumer extends LitElement {
384 readonly queryKey = key
385​
386 readonly query = createQueryController(this, {
387 queryKey: this.queryKey,
388 queryFn: () => sleep(10).then(() => 'query-ok'),
389 retry: false,
390 })
391​
392 readonly isFetching = useIsFetching(this, { queryKey: this.queryKey })
393 }
394 customElements.define(generateElementName(), Consumer)
395 const consumer = new Consumer()
396​
397 expect(consumer.query().status).toBe('pending')
398 expect(consumer.isFetching()).toBe(0)
399​
400 container.append(consumer)
401​
402 await vi.advanceTimersByTimeAsync(0)
403 expect(() => consumer.query()).toThrow(/No QueryClient available/)
404 expect(() => consumer.isFetching()).toThrow(/No QueryClient available/)
405​
406 const provider = document.createElement(
407 providerTagName,
408 ) as QueryClientProvider
409 provider.client = queryClient
410 provider.append(consumer)
411​
412 container.append(provider)
413 await provider.updateComplete
414 await consumer.updateComplete
415​
416 expect(consumer.isFetching()).toBe(1)
417 await vi.advanceTimersByTimeAsync(10)
418 expect(consumer.query().isSuccess).toBe(true)
419 expect(consumer.isFetching()).toBe(0)
420​
421 consumer.query.destroy()
422 consumer.isFetching.destroy()
423 provider.remove()
424 })
425​
426 it('should not throw on an already-connected host with an explicit client', async () => {
427 const key = queryKey()
428​
429 class Producer extends LitElement {
430 readonly query = createQueryController(
431 this,
432 {
433 queryKey: key,
434 queryFn: () => sleep(10).then(() => 'query-ok'),
435 retry: false,
436 },
437 queryClient,
438 )
439 }
440 customElements.define(generateElementName(), Producer)
441 const producer = new Producer()
442 container.append(producer)
443​
444 await vi.advanceTimersByTimeAsync(0)
445 expect(queryClient.isFetching()).toBe(1)
446​
447 class Host extends LitElement {
448 isFetching?: IsFetchingAccessor
449 }
450 customElements.define(generateElementName(), Host)
451 const host = new Host()
452 container.append(host)
453 await host.updateComplete
454​
455 // Lit calls hostConnected immediately when a controller is added to an
456 // already-connected host
457 host.isFetching = useIsFetching(host, {}, queryClient)
458 const { isFetching } = host
459​
460 expect(isFetching()).toBe(1)
461 await vi.advanceTimersByTimeAsync(10)
462 expect(isFetching()).toBe(0)
463​
464 isFetching.destroy()
465 })
466})