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

inject-query.test.ts

686 lines20.5 KB

1import {
2 ApplicationRef,
3 Component,
4 Injector,
5 computed,
6 input,
7 provideZonelessChangeDetection,
8 signal,
9} from '@angular/core'
10import { TestBed } from '@angular/core/testing'
11import { HttpClient, provideHttpClient } from '@angular/common/http'
12import {
13 HttpTestingController,
14 provideHttpClientTesting,
15} from '@angular/common/http/testing'
16import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
17import { render } from '@testing-library/angular'
18import { createKey, sleep } from '@tanstack/query-test-utils'
19import { lastValueFrom } from 'rxjs'
20import {
21 QueryCache,
22 QueryClient,
23 injectQuery,
24 provideIsRestoring,
25 provideTanStackQuery,
26} from '..'
27import { setSignalInputs } from './test-utils'
28import type { Query } from '..'
29​
30describe('injectQuery', () => {
31 let queryCache: QueryCache
32 let queryClient: QueryClient
33​
34 beforeEach(() => {
35 vi.useFakeTimers()
36 queryCache = new QueryCache()
37 queryClient = new QueryClient({ queryCache })
38 TestBed.configureTestingModule({
39 providers: [
40 provideZonelessChangeDetection(),
41 provideTanStackQuery(queryClient),
42 ],
43 })
44 })
45​
46 afterEach(() => {
47 vi.useRealTimers()
48 })
49​
50 it('should return pending status initially', () => {
51 const key = createKey()
52 const query = TestBed.runInInjectionContext(() => {
53 return injectQuery(() => ({
54 queryKey: key,
55 queryFn: () => sleep(10).then(() => 'Some data'),
56 }))
57 })
58​
59 expect(query.status()).toBe('pending')
60 expect(query.isPending()).toBe(true)
61 expect(query.isFetching()).toBe(true)
62 expect(query.isStale()).toBe(true)
63 expect(query.isFetched()).toBe(false)
64 })
65​
66 it('should resolve to success and update signal: injectQuery()', async () => {
67 const key = createKey()
68​
69 @Component({
70 template: `
71 <div>status: {{ query.status() }}</div>
72 <div>data: {{ query.data() ?? 'none' }}</div>
73 <div>isPending: {{ query.isPending() }}</div>
74 <div>isFetching: {{ query.isFetching() }}</div>
75 <div>isFetched: {{ query.isFetched() }}</div>
76 <div>isSuccess: {{ query.isSuccess() }}</div>
77 `,
78 })
79 class Page {
80 readonly query = injectQuery(() => ({
81 queryKey: key,
82 queryFn: () => sleep(10).then(() => 'result2'),
83 }))
84 }
85​
86 const rendered = await render(Page)
87​
88 await vi.advanceTimersByTimeAsync(11)
89 rendered.fixture.detectChanges()
90 expect(rendered.getByText('status: success')).toBeInTheDocument()
91 expect(rendered.getByText('data: result2')).toBeInTheDocument()
92 expect(rendered.getByText('isPending: false')).toBeInTheDocument()
93 expect(rendered.getByText('isFetching: false')).toBeInTheDocument()
94 expect(rendered.getByText('isFetched: true')).toBeInTheDocument()
95 expect(rendered.getByText('isSuccess: true')).toBeInTheDocument()
96 })
97​
98 it('should reject and update signal', async () => {
99 const key = createKey()
100​
101 @Component({
102 template: `
103 <div>status: {{ query.status() }}</div>
104 <div>data: {{ query.data() ?? 'none' }}</div>
105 <div>error: {{ query.error()?.message ?? 'none' }}</div>
106 <div>isPending: {{ query.isPending() }}</div>
107 <div>isFetching: {{ query.isFetching() }}</div>
108 <div>isError: {{ query.isError() }}</div>
109 <div>failureCount: {{ query.failureCount() }}</div>
110 <div>failureReason: {{ query.failureReason()?.message ?? 'none' }}</div>
111 `,
112 })
113 class Page {
114 readonly query = injectQuery(() => ({
115 retry: false,
116 queryKey: key,
117 queryFn: () =>
118 sleep(10).then(() => Promise.reject(new Error('Some error'))),
119 }))
120 }
121​
122 const rendered = await render(Page)
123​
124 await vi.advanceTimersByTimeAsync(11)
125 rendered.fixture.detectChanges()
126 expect(rendered.getByText('status: error')).toBeInTheDocument()
127 expect(rendered.getByText('data: none')).toBeInTheDocument()
128 expect(rendered.getByText('error: Some error')).toBeInTheDocument()
129 expect(rendered.getByText('isPending: false')).toBeInTheDocument()
130 expect(rendered.getByText('isFetching: false')).toBeInTheDocument()
131 expect(rendered.getByText('isError: true')).toBeInTheDocument()
132 expect(rendered.getByText('failureCount: 1')).toBeInTheDocument()
133 expect(rendered.getByText('failureReason: Some error')).toBeInTheDocument()
134 })
135​
136 it('should be able to select a part of the data with select', async () => {
137 const key = createKey()
138​
139 @Component({
140 template: `<div>data: {{ query.data() ?? 'none' }}</div>`,
141 })
142 class Page {
143 readonly query = injectQuery<{ name: string }, Error, string>(() => ({
144 queryKey: key,
145 queryFn: () => sleep(10).then(() => ({ name: 'test' })),
146 select: (data) => data.name,
147 }))
148 }
149​
150 const rendered = await render(Page)
151​
152 expect(rendered.getByText('data: none')).toBeInTheDocument()
153 await vi.advanceTimersByTimeAsync(11)
154 rendered.fixture.detectChanges()
155 expect(rendered.getByText('data: test')).toBeInTheDocument()
156 })
157​
158 it('should show placeholderData until queryFn resolves and then expose real data', async () => {
159 const key = createKey()
160​
161 @Component({
162 template: `
163 <div>data: {{ query.data() }}</div>
164 <div>isPlaceholderData: {{ query.isPlaceholderData() }}</div>
165 <div>isSuccess: {{ query.isSuccess() }}</div>
166 `,
167 })
168 class Page {
169 readonly query = injectQuery(() => ({
170 queryKey: key,
171 queryFn: () => sleep(10).then(() => 'real-data'),
172 placeholderData: 'placeholder',
173 }))
174 }
175​
176 const rendered = await render(Page)
177​
178 expect(rendered.getByText('data: placeholder')).toBeInTheDocument()
179 expect(rendered.getByText('isPlaceholderData: true')).toBeInTheDocument()
180 expect(rendered.getByText('isSuccess: true')).toBeInTheDocument()
181 await vi.advanceTimersByTimeAsync(11)
182 rendered.fixture.detectChanges()
183 expect(rendered.getByText('data: real-data')).toBeInTheDocument()
184 expect(rendered.getByText('isPlaceholderData: false')).toBeInTheDocument()
185 expect(rendered.getByText('isSuccess: true')).toBeInTheDocument()
186 })
187​
188 it('should update query on options contained signal change', async () => {
189 const key1 = createKey()
190 const key2 = createKey()
191 const key = signal(key1)
192 const queryFn = vi.fn<() => Promise<string>>(() =>
193 sleep(10).then(() => 'Some data'),
194 )
195​
196 const query = TestBed.runInInjectionContext(() => {
197 return injectQuery(() => ({
198 queryKey: key(),
199 queryFn,
200 }))
201 })
202​
203 await vi.advanceTimersByTimeAsync(0)
204 expect(queryFn).toHaveBeenCalledTimes(1)
205 await vi.advanceTimersByTimeAsync(10)
206 expect(query.status()).toBe('success')
207​
208 key.set(key2)
209 TestBed.tick()
210 expect(queryFn).toHaveBeenCalledTimes(2)
211 // should call queryFn with context containing the new queryKey
212 expect(queryFn).toHaveBeenNthCalledWith(
213 2,
214 expect.objectContaining({
215 client: queryClient,
216 meta: undefined,
217 queryKey: key2,
218 signal: expect.anything(),
219 }),
220 )
221 })
222​
223 it('should only run query once enabled signal is set to true', async () => {
224 const key = createKey()
225 const queryFn = vi.fn<() => Promise<string>>(() =>
226 sleep(10).then(() => 'Some data'),
227 )
228 const enabled = signal(false)
229​
230 const query = TestBed.runInInjectionContext(() => {
231 return injectQuery(() => ({
232 queryKey: key,
233 queryFn,
234 enabled: enabled(),
235 }))
236 })
237​
238 expect(queryFn).not.toHaveBeenCalled()
239 expect(query.status()).toBe('pending')
240​
241 enabled.set(true)
242 await vi.advanceTimersByTimeAsync(10)
243 expect(queryFn).toHaveBeenCalledTimes(1)
244 expect(query.status()).toBe('success')
245 })
246​
247 it('should not fetch while the enabled signal is false, and fetch again once it is truthy', async () => {
248 const key = createKey()
249 const queryFn = vi.fn<() => Promise<string>>(() =>
250 sleep(10).then(() => 'Some data'),
251 )
252 const filter = signal('a')
253​
254 const query = TestBed.runInInjectionContext(() => {
255 return injectQuery(() => ({
256 queryKey: [...key, filter()],
257 queryFn,
258 enabled: !!filter(),
259 }))
260 })
261​
262 await vi.advanceTimersByTimeAsync(10)
263 expect(queryFn).toHaveBeenCalledTimes(1)
264 expect(query.status()).toBe('success')
265​
266 filter.set('')
267 await vi.advanceTimersByTimeAsync(10)
268 expect(queryFn).toHaveBeenCalledTimes(1)
269 expect(query.isFetching()).toBe(false)
270​
271 filter.set('b')
272 await vi.advanceTimersByTimeAsync(10)
273 expect(queryFn).toHaveBeenCalledTimes(2)
274 })
275​
276 it('should properly execute dependent queries', async () => {
277 const key1 = createKey()
278 const key2 = createKey()
279​
280 const query1 = TestBed.runInInjectionContext(() => {
281 return injectQuery(() => ({
282 queryKey: key1,
283 queryFn: () => sleep(10).then(() => 'Some data'),
284 }))
285 })
286​
287 const dependentQueryFn = vi.fn<() => Promise<string>>(() =>
288 sleep(1000).then(() => 'Some data'),
289 )
290​
291 const query2 = TestBed.runInInjectionContext(() => {
292 return injectQuery(
293 computed(() => ({
294 queryKey: key2,
295 queryFn: dependentQueryFn,
296 enabled: !!query1.data(),
297 })),
298 )
299 })
300​
301 expect(query1.data()).toBeUndefined()
302 expect(query2.fetchStatus()).toBe('idle')
303 expect(dependentQueryFn).not.toHaveBeenCalled()
304 await vi.advanceTimersByTimeAsync(11)
305 expect(query1.data()).toBe('Some data')
306 expect(query2.fetchStatus()).toBe('fetching')
307 await vi.advanceTimersByTimeAsync(1002)
308 expect(query2.fetchStatus()).toBe('idle')
309 expect(query2.status()).toBe('success')
310 expect(dependentQueryFn).toHaveBeenCalledTimes(1)
311 expect(dependentQueryFn).toHaveBeenCalledWith(
312 expect.objectContaining({ queryKey: key2 }),
313 )
314 })
315​
316 it('should use the current value for the queryKey when refetch is called', async () => {
317 const key = createKey()
318 const queryFn = vi.fn<() => Promise<string>>(() =>
319 sleep(10).then(() => 'Some data'),
320 )
321 const keySignal = signal('key11')
322​
323 const query = TestBed.runInInjectionContext(() => {
324 return injectQuery(() => ({
325 queryKey: [...key, keySignal()],
326 queryFn,
327 enabled: false,
328 }))
329 })
330​
331 expect(queryFn).not.toHaveBeenCalled()
332​
333 void query.refetch()
334 await vi.advanceTimersByTimeAsync(10)
335 expect(queryFn).toHaveBeenCalledTimes(1)
336 expect(queryFn).toHaveBeenNthCalledWith(
337 1,
338 expect.objectContaining({
339 queryKey: [...key, 'key11'],
340 }),
341 )
342​
343 keySignal.set('key12')
344​
345 void query.refetch()
346 await vi.advanceTimersByTimeAsync(10)
347 expect(queryFn).toHaveBeenCalledTimes(2)
348 expect(queryFn).toHaveBeenNthCalledWith(
349 2,
350 expect.objectContaining({
351 queryKey: [...key, 'key12'],
352 }),
353 )
354 expect(query.data()).toBe('Some data')
355 })
356​
357 it('should keep initialData visible alongside the error when a refetch fails', async () => {
358 const key = createKey()
359​
360 @Component({
361 template: `
362 <div>data: {{ query.data() }}</div>
363 <div>isError: {{ query.isError() }}</div>
364 `,
365 })
366 class Page {
367 readonly query = injectQuery(() => ({
368 queryKey: key,
369 queryFn: () =>
370 sleep(10).then(() => Promise.reject(new Error('Some error'))),
371 initialData: 'initial',
372 retry: false,
373 }))
374 }
375​
376 const rendered = await render(Page)
377​
378 expect(rendered.getByText('data: initial')).toBeInTheDocument()
379 expect(rendered.getByText('isError: false')).toBeInTheDocument()
380 await vi.advanceTimersByTimeAsync(11)
381 rendered.fixture.detectChanges()
382 expect(rendered.getByText('data: initial')).toBeInTheDocument()
383 expect(rendered.getByText('isError: true')).toBeInTheDocument()
384 })
385​
386 describe('throwOnError', () => {
387 it('should evaluate throwOnError when query is expected to throw', async () => {
388 const key = createKey()
389 const throwOnError = vi.fn<(error: Error, query: Query) => boolean>()
390 TestBed.runInInjectionContext(() => {
391 return injectQuery(() => ({
392 queryKey: key,
393 queryFn: () =>
394 sleep(10).then(() => Promise.reject(new Error('Some error'))),
395 retry: false,
396 throwOnError,
397 }))
398 })
399​
400 await vi.advanceTimersByTimeAsync(11)
401 expect(throwOnError).toHaveBeenCalledTimes(1)
402 expect(throwOnError).toHaveBeenCalledWith(
403 Error('Some error'),
404 expect.objectContaining({
405 state: expect.objectContaining({ status: 'error' }),
406 }),
407 )
408 })
409​
410 it('should throw when throwOnError is true', async () => {
411 const key = createKey()
412 TestBed.runInInjectionContext(() => {
413 return injectQuery(() => ({
414 queryKey: key,
415 queryFn: () =>
416 sleep(0).then(() => Promise.reject(new Error('Some error'))),
417 throwOnError: true,
418 }))
419 })
420​
421 await expect(vi.runAllTimersAsync()).rejects.toThrow('Some error')
422 })
423​
424 it('should throw when throwOnError function returns true', async () => {
425 const key = createKey()
426 TestBed.runInInjectionContext(() => {
427 return injectQuery(() => ({
428 queryKey: key,
429 queryFn: () =>
430 sleep(0).then(() => Promise.reject(new Error('Some error'))),
431 throwOnError: () => true,
432 }))
433 })
434​
435 await expect(vi.runAllTimersAsync()).rejects.toThrow('Some error')
436 })
437 })
438​
439 it('should render with required signal inputs', async () => {
440 @Component({
441 selector: 'app-fake',
442 template: `{{ query.data() }}`,
443 })
444 class FakeComponent {
445 name = input.required<string>()
446​
447 query = injectQuery(() => ({
448 queryKey: ['fake', this.name()],
449 queryFn: () => this.name(),
450 }))
451 }
452​
453 const fixture = TestBed.createComponent(FakeComponent)
454 setSignalInputs(fixture.componentInstance, {
455 name: 'signal-input-required-test',
456 })
457​
458 fixture.detectChanges()
459 await vi.advanceTimersByTimeAsync(0)
460 expect(fixture.componentInstance.query.data()).toBe(
461 'signal-input-required-test',
462 )
463 })
464​
465 describe('isRestoring', () => {
466 it('should not fetch for the duration of the restoring period when isRestoring is true', async () => {
467 const key = createKey()
468 const queryFn = vi.fn<() => Promise<string>>(() =>
469 sleep(10).then(() => 'data'),
470 )
471​
472 TestBed.configureTestingModule({
473 providers: [provideIsRestoring(signal(true).asReadonly())],
474 })
475​
476 const query = TestBed.runInInjectionContext(() =>
477 injectQuery(() => ({
478 queryKey: key,
479 queryFn,
480 })),
481 )
482​
483 await vi.advanceTimersByTimeAsync(0)
484 expect(query.status()).toBe('pending')
485 expect(query.fetchStatus()).toBe('idle')
486 expect(query.data()).toBeUndefined()
487 expect(queryFn).toHaveBeenCalledTimes(0)
488 await vi.advanceTimersByTimeAsync(10)
489 expect(query.status()).toBe('pending')
490 expect(query.fetchStatus()).toBe('idle')
491 expect(query.data()).toBeUndefined()
492 expect(queryFn).toHaveBeenCalledTimes(0)
493 })
494 })
495​
496 describe('injection context', () => {
497 it('should throw NG0203 with descriptive error outside injection context', () => {
498 const key = createKey()
499 expect(() => {
500 injectQuery(() => ({
501 queryKey: key,
502 queryFn: () => sleep(0).then(() => 'Some data'),
503 }))
504 }).toThrow(/NG0203(.*?)injectQuery/)
505 })
506​
507 it('should be usable outside injection context when passing an injector', () => {
508 const key = createKey()
509 const query = injectQuery(
510 () => ({
511 queryKey: key,
512 queryFn: () => sleep(0).then(() => 'Some data'),
513 }),
514 {
515 injector: TestBed.inject(Injector),
516 },
517 )
518​
519 expect(query.status()).toBe('pending')
520 })
521​
522 it('should complete queries before whenStable() resolves', async () => {
523 const key = createKey()
524 const app = TestBed.inject(ApplicationRef)
525​
526 const query = TestBed.runInInjectionContext(() =>
527 injectQuery(() => ({
528 queryKey: key,
529 queryFn: () => sleep(50).then(() => 'test data'),
530 })),
531 )
532​
533 expect(query.status()).toBe('pending')
534 expect(query.data()).toBeUndefined()
535​
536 const stablePromise = app.whenStable()
537 await vi.advanceTimersByTimeAsync(60)
538 await stablePromise
539 expect(query.status()).toBe('success')
540 expect(query.data()).toBe('test data')
541 })
542​
543 it('should complete HttpClient-based queries before whenStable() resolves', async () => {
544 TestBed.configureTestingModule({
545 providers: [provideHttpClient(), provideHttpClientTesting()],
546 })
547​
548 const app = TestBed.inject(ApplicationRef)
549 const httpClient = TestBed.inject(HttpClient)
550 const httpTestingController = TestBed.inject(HttpTestingController)
551​
552 // Create a query using HttpClient
553 const key = createKey()
554 const query = TestBed.runInInjectionContext(() =>
555 injectQuery(() => ({
556 queryKey: key,
557 queryFn: () =>
558 lastValueFrom(httpClient.get<{ message: string }>('/api/test')),
559 })),
560 )
561​
562 // Schedule the HTTP response
563 setTimeout(() => {
564 const req = httpTestingController.expectOne('/api/test')
565 req.flush({ message: 'http test data' })
566 }, 10)
567​
568 // Initial state
569 expect(query.status()).toBe('pending')
570​
571 // Advance timers and wait for Angular to be "stable"
572 const stablePromise = app.whenStable()
573 await vi.advanceTimersByTimeAsync(20)
574 await stablePromise
575​
576 // Query should be complete after whenStable() thanks to PendingTasks integration
577 expect(query.status()).toBe('success')
578 expect(query.data()).toStrictEqual({ message: 'http test data' })
579​
580 httpTestingController.verify()
581 })
582​
583 it('should handle synchronous queryFn with staleTime', async () => {
584 const app = TestBed.inject(ApplicationRef)
585 let callCount = 0
586​
587 const key = createKey()
588 const query = TestBed.runInInjectionContext(() =>
589 injectQuery(() => ({
590 queryKey: key,
591 staleTime: 1000,
592 queryFn: () => {
593 callCount++
594 return `sync-data-${callCount}`
595 },
596 })),
597 )
598​
599 // Synchronize pending effects
600 TestBed.tick()
601​
602 const stablePromise = app.whenStable()
603 await stablePromise
604 expect(query.status()).toBe('success')
605 expect(query.data()).toBe('sync-data-1')
606 expect(callCount).toBe(1)
607​
608 await query.refetch()
609 await Promise.resolve()
610 await vi.runAllTimersAsync()
611 await app.whenStable()
612 expect(query.status()).toBe('success')
613 expect(query.data()).toBe('sync-data-2')
614 expect(callCount).toBe(2)
615 })
616​
617 it('should handle enabled/disabled transitions with synchronous queryFn', async () => {
618 const app = TestBed.inject(ApplicationRef)
619 const enabledSignal = signal(false)
620 let callCount = 0
621​
622 const key = createKey()
623 const query = TestBed.runInInjectionContext(() =>
624 injectQuery(() => ({
625 queryKey: key,
626 enabled: enabledSignal(),
627 queryFn: () => {
628 callCount++
629 return `sync-data-${callCount}`
630 },
631 })),
632 )
633​
634 // Initially disabled
635 TestBed.tick()
636 await app.whenStable()
637 expect(query.status()).toBe('pending')
638 expect(query.data()).toBeUndefined()
639 expect(callCount).toBe(0)
640​
641 // Enable the query
642 enabledSignal.set(true)
643 TestBed.tick()
644 await app.whenStable()
645 expect(query.status()).toBe('success')
646 expect(query.data()).toBe('sync-data-1')
647 expect(callCount).toBe(1)
648 })
649​
650 it('should handle query invalidation with synchronous data', async () => {
651 const app = TestBed.inject(ApplicationRef)
652 const testKey = createKey()
653 let callCount = 0
654​
655 const query = TestBed.runInInjectionContext(() =>
656 injectQuery(() => ({
657 queryKey: testKey,
658 queryFn: () => {
659 callCount++
660 return `sync-data-${callCount}`
661 },
662 })),
663 )
664​
665 // Synchronize pending effects
666 TestBed.tick()
667 await app.whenStable()
668 expect(query.status()).toBe('success')
669 expect(query.data()).toBe('sync-data-1')
670 expect(callCount).toBe(1)
671​
672 // Invalidate the query
673 queryClient.invalidateQueries({ queryKey: testKey })
674 TestBed.tick()
675​
676 // Wait for the invalidation to trigger a refetch
677 await Promise.resolve()
678 await vi.advanceTimersByTimeAsync(10)
679 TestBed.tick()
680 await app.whenStable()
681 expect(query.status()).toBe('success')
682 expect(query.data()).toBe('sync-data-2')
683 expect(callCount).toBe(2)
684 })
685 })
686})