Open History to see the last commit
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'
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 = queryKey()
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 = queryKey()
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 = queryKey()
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 = queryKey()
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 = queryKey()
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 = queryKey()
190 const key2 = queryKey()
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(2, {
213 client: queryClient,
214 meta: undefined,
215 queryKey: key2,
216 signal: expect.anything(),
217 })
218 })
219β
220 it('should only run query once enabled signal is set to true', async () => {
221 const key = queryKey()
222 const queryFn = vi.fn<() => Promise<string>>(() =>
223 sleep(10).then(() => 'Some data'),
224 )
225 const enabled = signal(false)
226β
227 const query = TestBed.runInInjectionContext(() => {
228 return injectQuery(() => ({
229 queryKey: key,
230 queryFn,
231 enabled: enabled(),
232 }))
233 })
234β
235 expect(queryFn).not.toHaveBeenCalled()
236 expect(query.status()).toBe('pending')
237β
238 enabled.set(true)
239 await vi.advanceTimersByTimeAsync(10)
240 expect(queryFn).toHaveBeenCalledTimes(1)
241 expect(query.status()).toBe('success')
242 })
243β
244 it('should not fetch while the enabled signal is false, and fetch again once it is truthy', async () => {
245 const key = queryKey()
246 const queryFn = vi.fn<() => Promise<string>>(() =>
247 sleep(10).then(() => 'Some data'),
248 )
249 const filter = signal('a')
250β
251 const query = TestBed.runInInjectionContext(() => {
252 return injectQuery(() => ({
253 queryKey: [...key, filter()],
254 queryFn,
255 enabled: !!filter(),
256 }))
257 })
258β
259 await vi.advanceTimersByTimeAsync(10)
260 expect(queryFn).toHaveBeenCalledTimes(1)
261 expect(query.status()).toBe('success')
262β
263 filter.set('')
264 await vi.advanceTimersByTimeAsync(10)
265 expect(queryFn).toHaveBeenCalledTimes(1)
266 expect(query.isFetching()).toBe(false)
267β
268 filter.set('b')
269 await vi.advanceTimersByTimeAsync(10)
270 expect(queryFn).toHaveBeenCalledTimes(2)
271 })
272β
273 it('should properly execute dependent queries', async () => {
274 const key1 = queryKey()
275 const key2 = queryKey()
276β
277 const query1 = TestBed.runInInjectionContext(() => {
278 return injectQuery(() => ({
279 queryKey: key1,
280 queryFn: () => sleep(10).then(() => 'Some data'),
281 }))
282 })
283β
284 const dependentQueryFn = vi.fn<() => Promise<string>>(() =>
285 sleep(1000).then(() => 'Some data'),
286 )
287β
288 const query2 = TestBed.runInInjectionContext(() => {
289 return injectQuery(
290 computed(() => ({
291 queryKey: key2,
292 queryFn: dependentQueryFn,
293 enabled: !!query1.data(),
294 })),
295 )
296 })
297β
298 expect(query1.data()).toBeUndefined()
299 expect(query2.fetchStatus()).toBe('idle')
300 expect(dependentQueryFn).not.toHaveBeenCalled()
301 await vi.advanceTimersByTimeAsync(11)
302 expect(query1.data()).toBe('Some data')
303 expect(query2.fetchStatus()).toBe('fetching')
304 await vi.advanceTimersByTimeAsync(1002)
305 expect(query2.fetchStatus()).toBe('idle')
306 expect(query2.status()).toBe('success')
307 expect(dependentQueryFn).toHaveBeenCalledTimes(1)
308 expect(dependentQueryFn).toHaveBeenCalledWith(
309 expect.objectContaining({ queryKey: key2 }),
310 )
311 })
312β
313 it('should use the current value for the queryKey when refetch is called', async () => {
314 const key = queryKey()
315 const queryFn = vi.fn<() => Promise<string>>(() =>
316 sleep(10).then(() => 'Some data'),
317 )
318 const keySignal = signal('key11')
319β
320 const query = TestBed.runInInjectionContext(() => {
321 return injectQuery(() => ({
322 queryKey: [...key, keySignal()],
323 queryFn,
324 enabled: false,
325 }))
326 })
327β
328 expect(queryFn).not.toHaveBeenCalled()
329β
330 void query.refetch()
331 await vi.advanceTimersByTimeAsync(10)
332 expect(queryFn).toHaveBeenCalledTimes(1)
333 expect(queryFn).toHaveBeenNthCalledWith(
334 1,
335 expect.objectContaining({
336 queryKey: [...key, 'key11'],
337 }),
338 )
339β
340 keySignal.set('key12')
341β
342 void query.refetch()
343 await vi.advanceTimersByTimeAsync(10)
344 expect(queryFn).toHaveBeenCalledTimes(2)
345 expect(queryFn).toHaveBeenNthCalledWith(
346 2,
347 expect.objectContaining({
348 queryKey: [...key, 'key12'],
349 }),
350 )
351 expect(query.data()).toBe('Some data')
352 })
353β
354 it('should keep initialData visible alongside the error when a refetch fails', async () => {
355 const key = queryKey()
356β
357 @Component({
358 template: `
359 <div>data: {{ query.data() }}</div>
360 <div>isError: {{ query.isError() }}</div>
361 `,
362 })
363 class Page {
364 readonly query = injectQuery(() => ({
365 queryKey: key,
366 queryFn: () =>
367 sleep(10).then(() => Promise.reject(new Error('Some error'))),
368 initialData: 'initial',
369 retry: false,
370 }))
371 }
372β
373 const rendered = await render(Page)
374β
375 expect(rendered.getByText('data: initial')).toBeInTheDocument()
376 expect(rendered.getByText('isError: false')).toBeInTheDocument()
377 await vi.advanceTimersByTimeAsync(11)
378 rendered.fixture.detectChanges()
379 expect(rendered.getByText('data: initial')).toBeInTheDocument()
380 expect(rendered.getByText('isError: true')).toBeInTheDocument()
381 })
382β
383 describe('throwOnError', () => {
384 it('should evaluate throwOnError when query is expected to throw', async () => {
385 const key = queryKey()
386 const throwOnError = vi.fn<(error: Error, query: Query) => boolean>()
387 TestBed.runInInjectionContext(() => {
388 return injectQuery(() => ({
389 queryKey: key,
390 queryFn: () =>
391 sleep(10).then(() => Promise.reject(new Error('Some error'))),
392 retry: false,
393 throwOnError,
394 }))
395 })
396β
397 await vi.advanceTimersByTimeAsync(11)
398 expect(throwOnError).toHaveBeenCalledTimes(1)
399 expect(throwOnError).toHaveBeenCalledWith(
400 Error('Some error'),
401 expect.objectContaining({
402 state: expect.objectContaining({ status: 'error' }),
403 }),
404 )
405 })
406β
407 it('should throw when throwOnError is true', async () => {
408 const key = queryKey()
409 TestBed.runInInjectionContext(() => {
410 return injectQuery(() => ({
411 queryKey: key,
412 queryFn: () =>
413 sleep(0).then(() => Promise.reject(new Error('Some error'))),
414 throwOnError: true,
415 }))
416 })
417β
418 await expect(vi.runAllTimersAsync()).rejects.toThrow('Some error')
419 })
420β
421 it('should throw when throwOnError function returns true', async () => {
422 const key = queryKey()
423 TestBed.runInInjectionContext(() => {
424 return injectQuery(() => ({
425 queryKey: key,
426 queryFn: () =>
427 sleep(0).then(() => Promise.reject(new Error('Some error'))),
428 throwOnError: () => true,
429 }))
430 })
431β
432 await expect(vi.runAllTimersAsync()).rejects.toThrow('Some error')
433 })
434 })
435β
436 it('should render with required signal inputs', async () => {
437 @Component({
438 selector: 'app-fake',
439 template: `{{ query.data() }}`,
440 })
441 class FakeComponent {
442 name = input.required<string>()
443β
444 query = injectQuery(() => ({
445 queryKey: ['fake', this.name()],
446 queryFn: () => this.name(),
447 }))
448 }
449β
450 const fixture = TestBed.createComponent(FakeComponent)
451 setSignalInputs(fixture.componentInstance, {
452 name: 'signal-input-required-test',
453 })
454β
455 fixture.detectChanges()
456 await vi.advanceTimersByTimeAsync(0)
457 expect(fixture.componentInstance.query.data()).toBe(
458 'signal-input-required-test',
459 )
460 })
461β
462 describe('isRestoring', () => {
463 it('should not fetch for the duration of the restoring period when isRestoring is true', async () => {
464 const key = queryKey()
465 const queryFn = vi.fn<() => Promise<string>>(() =>
466 sleep(10).then(() => 'data'),
467 )
468β
469 TestBed.configureTestingModule({
470 providers: [provideIsRestoring(signal(true).asReadonly())],
471 })
472β
473 const query = TestBed.runInInjectionContext(() =>
474 injectQuery(() => ({
475 queryKey: key,
476 queryFn,
477 })),
478 )
479β
480 await vi.advanceTimersByTimeAsync(0)
481 expect(query.status()).toBe('pending')
482 expect(query.fetchStatus()).toBe('idle')
483 expect(query.data()).toBeUndefined()
484 expect(queryFn).toHaveBeenCalledTimes(0)
485 await vi.advanceTimersByTimeAsync(10)
486 expect(query.status()).toBe('pending')
487 expect(query.fetchStatus()).toBe('idle')
488 expect(query.data()).toBeUndefined()
489 expect(queryFn).toHaveBeenCalledTimes(0)
490 })
491 })
492β
493 describe('injection context', () => {
494 it('should throw NG0203 with descriptive error outside injection context', () => {
495 const key = queryKey()
496 expect(() => {
497 injectQuery(() => ({
498 queryKey: key,
499 queryFn: () => sleep(0).then(() => 'Some data'),
500 }))
501 }).toThrow(/NG0203(.*?)injectQuery/)
502 })
503β
504 it('should be usable outside injection context when passing an injector', () => {
505 const key = queryKey()
506 const query = injectQuery(
507 () => ({
508 queryKey: key,
509 queryFn: () => sleep(0).then(() => 'Some data'),
510 }),
511 {
512 injector: TestBed.inject(Injector),
513 },
514 )
515β
516 expect(query.status()).toBe('pending')
517 })
518β
519 it('should complete queries before whenStable() resolves', async () => {
520 const key = queryKey()
521 const app = TestBed.inject(ApplicationRef)
522β
523 const query = TestBed.runInInjectionContext(() =>
524 injectQuery(() => ({
525 queryKey: key,
526 queryFn: () => sleep(50).then(() => 'test data'),
527 })),
528 )
529β
530 expect(query.status()).toBe('pending')
531 expect(query.data()).toBeUndefined()
532β
533 const stablePromise = app.whenStable()
534 await vi.advanceTimersByTimeAsync(60)
535 await stablePromise
536 expect(query.status()).toBe('success')
537 expect(query.data()).toBe('test data')
538 })
539β
540 it('should complete HttpClient-based queries before whenStable() resolves', async () => {
541 TestBed.configureTestingModule({
542 providers: [provideHttpClient(), provideHttpClientTesting()],
543 })
544β
545 const app = TestBed.inject(ApplicationRef)
546 const httpClient = TestBed.inject(HttpClient)
547 const httpTestingController = TestBed.inject(HttpTestingController)
548β
549 // Create a query using HttpClient
550 const key = queryKey()
551 const query = TestBed.runInInjectionContext(() =>
552 injectQuery(() => ({
553 queryKey: key,
554 queryFn: () =>
555 lastValueFrom(httpClient.get<{ message: string }>('/api/test')),
556 })),
557 )
558β
559 // Schedule the HTTP response
560 setTimeout(() => {
561 const req = httpTestingController.expectOne('/api/test')
562 req.flush({ message: 'http test data' })
563 }, 10)
564β
565 // Initial state
566 expect(query.status()).toBe('pending')
567β
568 // Advance timers and wait for Angular to be "stable"
569 const stablePromise = app.whenStable()
570 await vi.advanceTimersByTimeAsync(20)
571 await stablePromise
572β
573 // Query should be complete after whenStable() thanks to PendingTasks integration
574 expect(query.status()).toBe('success')
575 expect(query.data()).toStrictEqual({ message: 'http test data' })
576β
577 httpTestingController.verify()
578 })
579β
580 it('should handle synchronous queryFn with staleTime', async () => {
581 const app = TestBed.inject(ApplicationRef)
582 let callCount = 0
583β
584 const key = queryKey()
585 const query = TestBed.runInInjectionContext(() =>
586 injectQuery(() => ({
587 queryKey: key,
588 staleTime: 1000,
589 queryFn: () => {
590 callCount++
591 return `sync-data-${callCount}`
592 },
593 })),
594 )
595β
596 // Synchronize pending effects
597 TestBed.tick()
598β
599 const stablePromise = app.whenStable()
600 await stablePromise
601 expect(query.status()).toBe('success')
602 expect(query.data()).toBe('sync-data-1')
603 expect(callCount).toBe(1)
604β
605 await query.refetch()
606 await Promise.resolve()
607 await vi.runAllTimersAsync()
608 await app.whenStable()
609 expect(query.status()).toBe('success')
610 expect(query.data()).toBe('sync-data-2')
611 expect(callCount).toBe(2)
612 })
613β
614 it('should handle enabled/disabled transitions with synchronous queryFn', async () => {
615 const app = TestBed.inject(ApplicationRef)
616 const enabledSignal = signal(false)
617 let callCount = 0
618β
619 const key = queryKey()
620 const query = TestBed.runInInjectionContext(() =>
621 injectQuery(() => ({
622 queryKey: key,
623 enabled: enabledSignal(),
624 queryFn: () => {
625 callCount++
626 return `sync-data-${callCount}`
627 },
628 })),
629 )
630β
631 // Initially disabled
632 TestBed.tick()
633 await app.whenStable()
634 expect(query.status()).toBe('pending')
635 expect(query.data()).toBeUndefined()
636 expect(callCount).toBe(0)
637β
638 // Enable the query
639 enabledSignal.set(true)
640 TestBed.tick()
641 await app.whenStable()
642 expect(query.status()).toBe('success')
643 expect(query.data()).toBe('sync-data-1')
644 expect(callCount).toBe(1)
645 })
646β
647 it('should handle query invalidation with synchronous data', async () => {
648 const app = TestBed.inject(ApplicationRef)
649 const testKey = queryKey()
650 let callCount = 0
651β
652 const query = TestBed.runInInjectionContext(() =>
653 injectQuery(() => ({
654 queryKey: testKey,
655 queryFn: () => {
656 callCount++
657 return `sync-data-${callCount}`
658 },
659 })),
660 )
661β
662 // Synchronize pending effects
663 TestBed.tick()
664 await app.whenStable()
665 expect(query.status()).toBe('success')
666 expect(query.data()).toBe('sync-data-1')
667 expect(callCount).toBe(1)
668β
669 // Invalidate the query
670 queryClient.invalidateQueries({ queryKey: testKey })
671 TestBed.tick()
672β
673 // Wait for the invalidation to trigger a refetch
674 await Promise.resolve()
675 await vi.advanceTimersByTimeAsync(10)
676 TestBed.tick()
677 await app.whenStable()
678 expect(query.status()).toBe('success')
679 expect(query.data()).toBe('sync-data-2')
680 expect(callCount).toBe(2)
681 })
682 })
683})