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