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

inject-query.test.ts

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