Open History to see the last commit
1import {
2 Component,
3 Injectable,
4 Injector,
5 computed,
6 effect,
7 inject,
8 input,
9 signal,
10} from '@angular/core'
11import { TestBed, fakeAsync, flush, tick } from '@angular/core/testing'
12import { describe, expect, vi } from 'vitest'
13import { QueryCache, QueryClient, injectQuery, provideTanStackQuery } from '..'
14import {
15 delayedFetcher,
16 getSimpleFetcherWithReturnData,
17 queryKey,
18 rejectFetcher,
19 setSignalInputs,
20 simpleFetcher,
21} from './test-utils'
22import type { CreateQueryOptions, OmitKeyof, QueryFunction } from '..'
23β
24describe('injectQuery', () => {
25 let queryCache: QueryCache
26 let queryClient: QueryClient
27 beforeEach(() => {
28 queryCache = new QueryCache()
29 queryClient = new QueryClient({ queryCache })
30 TestBed.configureTestingModule({
31 providers: [provideTanStackQuery(queryClient)],
32 })
33 })
34β
35 test('should return the correct types', () => {
36 const key = queryKey()
37 // unspecified query function should default to unknown
38 const noQueryFn = TestBed.runInInjectionContext(() =>
39 injectQuery(() => ({
40 queryKey: key,
41 })),
42 )
43 expectTypeOf(noQueryFn.data()).toEqualTypeOf<unknown>()
44 expectTypeOf(noQueryFn.error()).toEqualTypeOf<Error | null>()
45β
46 // it should infer the result type from the query function
47 const fromQueryFn = TestBed.runInInjectionContext(() =>
48 injectQuery(() => ({
49 queryKey: key,
50 queryFn: () => 'test',
51 })),
52 )
53 expectTypeOf(fromQueryFn.data()).toEqualTypeOf<string | undefined>()
54 expectTypeOf(fromQueryFn.error()).toEqualTypeOf<Error | null>()
55β
56 // it should be possible to specify the result type
57 const withResult = TestBed.runInInjectionContext(() =>
58 injectQuery<string>(() => ({
59 queryKey: key,
60 queryFn: () => 'test',
61 })),
62 )
63 expectTypeOf(withResult.data()).toEqualTypeOf<string | undefined>()
64 expectTypeOf(withResult.error()).toEqualTypeOf<Error | null>()
65β
66 // it should be possible to specify the error type
67 type CustomErrorType = { message: string }
68 const withError = TestBed.runInInjectionContext(() =>
69 injectQuery<string, CustomErrorType>(() => ({
70 queryKey: key,
71 queryFn: () => 'test',
72 })),
73 )
74 expectTypeOf(withError.data()).toEqualTypeOf<string | undefined>()
75 expectTypeOf(withError.error()).toEqualTypeOf<CustomErrorType | null>()
76β
77 // it should infer the result type from the configuration
78 const withResultInfer = TestBed.runInInjectionContext(() =>
79 injectQuery(() => ({
80 queryKey: key,
81 queryFn: () => true,
82 })),
83 )
84 expectTypeOf(withResultInfer.data()).toEqualTypeOf<boolean | undefined>()
85 expectTypeOf(withResultInfer.error()).toEqualTypeOf<Error | null>()
86β
87 // it should be possible to specify a union type as result type
88 const unionTypeSync = TestBed.runInInjectionContext(() =>
89 injectQuery(() => ({
90 queryKey: key,
91 queryFn: () => (Math.random() > 0.5 ? ('a' as const) : ('b' as const)),
92 })),
93 )
94 expectTypeOf(unionTypeSync.data()).toEqualTypeOf<'a' | 'b' | undefined>()
95 const unionTypeAsync = TestBed.runInInjectionContext(() =>
96 injectQuery<'a' | 'b'>(() => ({
97 queryKey: key,
98 queryFn: () => Promise.resolve(Math.random() > 0.5 ? 'a' : 'b'),
99 })),
100 )
101 expectTypeOf(unionTypeAsync.data()).toEqualTypeOf<'a' | 'b' | undefined>()
102β
103 // it should error when the query function result does not match with the specified type
104 TestBed.runInInjectionContext(() =>
105 // @ts-expect-error
106 injectQuery<number>(() => ({ queryKey: key, queryFn: () => 'test' })),
107 )
108β
109 // it should infer the result type from a generic query function
110 /**
111 *
112 */
113 function queryFn<T = string>(): Promise<T> {
114 return Promise.resolve({} as T)
115 }
116β
117 const fromGenericQueryFn = TestBed.runInInjectionContext(() =>
118 injectQuery(() => ({
119 queryKey: key,
120 queryFn: () => queryFn(),
121 })),
122 )
123 expectTypeOf(fromGenericQueryFn.data()).toEqualTypeOf<string | undefined>()
124 expectTypeOf(fromGenericQueryFn.error()).toEqualTypeOf<Error | null>()
125β
126 // todo use query options?
127 const fromGenericOptionsQueryFn = TestBed.runInInjectionContext(() =>
128 injectQuery(() => ({
129 queryKey: key,
130 queryFn: () => queryFn(),
131 })),
132 )
133 expectTypeOf(fromGenericOptionsQueryFn.data()).toEqualTypeOf<
134 string | undefined
135 >()
136 expectTypeOf(
137 fromGenericOptionsQueryFn.error(),
138 ).toEqualTypeOf<Error | null>()
139β
140 type MyData = number
141 type MyQueryKey = readonly ['my-data', number]
142β
143 const getMyDataArrayKey: QueryFunction<MyData, MyQueryKey> = async ({
144 queryKey: [, n],
145 }) => {
146 return n + 42
147 }
148β
149 const fromMyDataArrayKeyQueryFn = TestBed.runInInjectionContext(() =>
150 injectQuery(() => ({
151 queryKey: ['my-data', 100] as const,
152 queryFn: getMyDataArrayKey,
153 })),
154 )
155 expectTypeOf(fromMyDataArrayKeyQueryFn.data()).toEqualTypeOf<
156 number | undefined
157 >()
158β
159 TestBed.runInInjectionContext(() =>
160 effect(() => {
161 if (fromPromiseAnyQueryFn.isSuccess()) {
162 expect(fromMyDataArrayKeyQueryFn.data()).toBe(142)
163 }
164 }),
165 )
166β
167 const getMyDataStringKey: QueryFunction<MyData, ['1']> = async (
168 context,
169 ) => {
170 expectTypeOf(context.queryKey).toEqualTypeOf<['1']>()
171 return Number(context.queryKey[0]) + 42
172 }
173β
174 const fromGetMyDataStringKeyQueryFn = TestBed.runInInjectionContext(() =>
175 injectQuery(() => ({
176 queryKey: ['1'] as ['1'],
177 queryFn: getMyDataStringKey,
178 })),
179 )
180 expectTypeOf(fromGetMyDataStringKeyQueryFn.data()).toEqualTypeOf<
181 number | undefined
182 >()
183β
184 TestBed.runInInjectionContext(() =>
185 effect(() => {
186 if (fromGetMyDataStringKeyQueryFn.isSuccess()) {
187 expect(fromGetMyDataStringKeyQueryFn.data()).toBe(43)
188 }
189 }),
190 )
191β
192 // it should handle query-functions that return Promise<any>
193 const fromPromiseAnyQueryFn = TestBed.runInInjectionContext(() =>
194 injectQuery(() => ({
195 queryKey: key,
196 queryFn: () => fetch('return Promise<any>').then((resp) => resp.json()),
197 })),
198 )
199 expectTypeOf(fromPromiseAnyQueryFn.data()).toEqualTypeOf<any | undefined>()
200β
201 // handles wrapped queries with custom fetcher passed as inline queryFn
202 const createWrappedQuery = <
203 TQueryKey extends [string, Record<string, unknown>?],
204 TQueryFnData,
205 TError,
206 TData = TQueryFnData,
207 >(
208 qk: TQueryKey,
209 fetcher: (
210 obj: TQueryKey[1],
211 token: string,
212 // return type must be wrapped with TQueryFnReturn
213 ) => Promise<TQueryFnData>,
214 options?: OmitKeyof<
215 CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
216 'queryKey' | 'queryFn' | 'initialData',
217 'safely'
218 >,
219 ) =>
220 injectQuery(() => ({
221 queryKey: qk,
222 queryFn: () => fetcher(qk[1], 'token'),
223 ...options,
224 }))
225 const fromWrappedQuery = TestBed.runInInjectionContext(() =>
226 createWrappedQuery([''], async () => '1'),
227 )
228 expectTypeOf(fromWrappedQuery.data()).toEqualTypeOf<string | undefined>()
229β
230 // handles wrapped queries with custom fetcher passed directly to createQuery
231 const createWrappedFuncStyleQuery = <
232 TQueryKey extends [string, Record<string, unknown>?],
233 TQueryFnData,
234 TError,
235 TData = TQueryFnData,
236 >(
237 qk: TQueryKey,
238 fetcher: () => Promise<TQueryFnData>,
239 options?: OmitKeyof<
240 CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
241 'queryKey' | 'queryFn' | 'initialData',
242 'safely'
243 >,
244 ) => injectQuery(() => ({ queryKey: qk, queryFn: fetcher, ...options }))
245 const fromWrappedFuncStyleQuery = TestBed.runInInjectionContext(() =>
246 createWrappedFuncStyleQuery([''], async () => true),
247 )
248 expectTypeOf(fromWrappedFuncStyleQuery.data()).toEqualTypeOf<
249 boolean | undefined
250 >()
251 })
252β
253 test('should return pending status initially', fakeAsync(() => {
254 const query = TestBed.runInInjectionContext(() => {
255 return injectQuery(() => ({
256 queryKey: ['key1'],
257 queryFn: simpleFetcher,
258 }))
259 })
260β
261 expect(query.status()).toBe('pending')
262 expect(query.isPending()).toBe(true)
263 expect(query.isFetching()).toBe(true)
264 expect(query.isStale()).toBe(true)
265 expect(query.isFetched()).toBe(false)
266 }))
267β
268 test('should resolve to success and update signal: injectQuery()', fakeAsync(() => {
269 const query = TestBed.runInInjectionContext(() => {
270 return injectQuery(() => ({
271 queryKey: ['key2'],
272 queryFn: getSimpleFetcherWithReturnData('result2'),
273 }))
274 })
275β
276 tick()
277β
278 expect(query.status()).toBe('success')
279 expect(query.data()).toBe('result2')
280 expect(query.isPending()).toBe(false)
281 expect(query.isFetching()).toBe(false)
282 expect(query.isFetched()).toBe(true)
283 expect(query.isSuccess()).toBe(true)
284 }))
285β
286 test('should reject and update signal', fakeAsync(() => {
287 const query = TestBed.runInInjectionContext(() => {
288 return injectQuery(() => ({
289 retry: false,
290 queryKey: ['key3'],
291 queryFn: rejectFetcher,
292 }))
293 })
294β
295 tick()
296β
297 expect(query.status()).toBe('error')
298 expect(query.data()).toBe(undefined)
299 expect(query.error()).toMatchObject({ message: 'Some error' })
300 expect(query.isPending()).toBe(false)
301 expect(query.isFetching()).toBe(false)
302 expect(query.isError()).toBe(true)
303 expect(query.failureCount()).toBe(1)
304 expect(query.failureReason()).toMatchObject({ message: 'Some error' })
305 }))
306β
307 test('should update query on options contained signal change', fakeAsync(() => {
308 const key = signal(['key6', 'key7'])
309 const spy = vi.fn(simpleFetcher)
310β
311 const query = TestBed.runInInjectionContext(() => {
312 return injectQuery(() => ({
313 queryKey: key(),
314 queryFn: spy,
315 }))
316 })
317 tick()
318 expect(spy).toHaveBeenCalledTimes(1)
319β
320 expect(query.status()).toBe('success')
321β
322 key.set(['key8'])
323 TestBed.flushEffects()
324β
325 expect(spy).toHaveBeenCalledTimes(2)
326 // should call queryFn with context containing the new queryKey
327 expect(spy).toBeCalledWith({
328 client: queryClient,
329 meta: undefined,
330 queryKey: ['key8'],
331 signal: expect.anything(),
332 })
333 }))
334β
335 test('should only run query once enabled signal is set to true', fakeAsync(() => {
336 const spy = vi.fn(simpleFetcher)
337 const enabled = signal(false)
338β
339 const query = TestBed.runInInjectionContext(() => {
340 return injectQuery(() => ({
341 queryKey: ['key9'],
342 queryFn: spy,
343 enabled: enabled(),
344 }))
345 })
346β
347 expect(spy).not.toHaveBeenCalled()
348 expect(query.status()).toBe('pending')
349β
350 enabled.set(true)
351 tick()
352 expect(spy).toHaveBeenCalledTimes(1)
353 expect(query.status()).toBe('success')
354 }))
355β
356 test('should properly execute dependant queries', fakeAsync(() => {
357 const query1 = TestBed.runInInjectionContext(() => {
358 return injectQuery(() => ({
359 queryKey: ['dependant1'],
360 queryFn: simpleFetcher,
361 }))
362 })
363β
364 const dependentQueryFn = vi.fn().mockImplementation(delayedFetcher(1000))
365β
366 const query2 = TestBed.runInInjectionContext(() => {
367 return injectQuery(
368 computed(() => ({
369 queryKey: ['dependant2'],
370 queryFn: dependentQueryFn,
371 enabled: !!query1.data(),
372 })),
373 )
374 })
375β
376 expect(query1.data()).toStrictEqual(undefined)
377 expect(query2.fetchStatus()).toStrictEqual('idle')
378 expect(dependentQueryFn).not.toHaveBeenCalled()
379β
380 tick()
381β
382 expect(query1.data()).toStrictEqual('Some data')
383 expect(query2.fetchStatus()).toStrictEqual('fetching')
384β
385 flush()
386β
387 expect(query2.fetchStatus()).toStrictEqual('idle')
388 expect(query2.status()).toStrictEqual('success')
389 expect(dependentQueryFn).toHaveBeenCalledTimes(1)
390 expect(dependentQueryFn).toHaveBeenCalledWith(
391 expect.objectContaining({ queryKey: ['dependant2'] }),
392 )
393 }))
394β
395 test('should use the current value for the queryKey when refetch is called', fakeAsync(() => {
396 const fetchFn = vi.fn(simpleFetcher)
397 const keySignal = signal('key11')
398β
399 const query = TestBed.runInInjectionContext(() => {
400 return injectQuery(() => ({
401 queryKey: ['key10', keySignal()],
402 queryFn: fetchFn,
403 enabled: false,
404 }))
405 })
406β
407 expect(fetchFn).not.toHaveBeenCalled()
408β
409 query.refetch().then(() => {
410 expect(fetchFn).toHaveBeenCalledTimes(1)
411 expect(fetchFn).toHaveBeenCalledWith(
412 expect.objectContaining({
413 queryKey: ['key10', 'key11'],
414 }),
415 )
416 })
417β
418 tick()
419β
420 keySignal.set('key12')
421β
422 TestBed.flushEffects()
423β
424 query.refetch().then(() => {
425 expect(fetchFn).toHaveBeenCalledTimes(2)
426 expect(fetchFn).toHaveBeenCalledWith(
427 expect.objectContaining({
428 queryKey: ['key10', 'key12'],
429 }),
430 )
431 })
432 }))
433β
434 describe('throwOnError', () => {
435 test('should evaluate throwOnError when query is expected to throw', fakeAsync(() => {
436 const boundaryFn = vi.fn()
437 TestBed.runInInjectionContext(() => {
438 return injectQuery(() => ({
439 queryKey: ['key12'],
440 queryFn: rejectFetcher,
441 throwOnError: boundaryFn,
442 }))
443 })
444β
445 flush()
446β
447 expect(boundaryFn).toHaveBeenCalledTimes(1)
448 expect(boundaryFn).toHaveBeenCalledWith(
449 Error('Some error'),
450 expect.objectContaining({
451 state: expect.objectContaining({ status: 'error' }),
452 }),
453 )
454 }))
455β
456 test('should throw when throwOnError is true', fakeAsync(() => {
457 TestBed.runInInjectionContext(() => {
458 return injectQuery(() => ({
459 queryKey: ['key13'],
460 queryFn: rejectFetcher,
461 throwOnError: true,
462 }))
463 })
464β
465 expect(() => {
466 flush()
467 }).toThrowError('Some error')
468 }))
469β
470 test('should throw when throwOnError function returns true', fakeAsync(() => {
471 TestBed.runInInjectionContext(() => {
472 return injectQuery(() => ({
473 queryKey: ['key14'],
474 queryFn: rejectFetcher,
475 throwOnError: () => true,
476 }))
477 })
478β
479 expect(() => {
480 flush()
481 }).toThrowError('Some error')
482 }))
483 })
484β
485 test('should set state to error when queryFn returns reject promise', fakeAsync(() => {
486 const query = TestBed.runInInjectionContext(() => {
487 return injectQuery(() => ({
488 retry: false,
489 queryKey: ['key15'],
490 queryFn: rejectFetcher,
491 }))
492 })
493β
494 expect(query.status()).toBe('pending')
495β
496 tick()
497β
498 expect(query.status()).toBe('error')
499 }))
500β
501 test('should render with required signal inputs', fakeAsync(() => {
502 @Component({
503 selector: 'app-fake',
504 template: `{{ query.data() }}`,
505 standalone: true,
506 })
507 class FakeComponent {
508 name = input.required<string>()
509β
510 query = injectQuery(() => ({
511 queryKey: ['fake', this.name()],
512 queryFn: () => this.name(),
513 }))
514 }
515β
516 const fixture = TestBed.createComponent(FakeComponent)
517 setSignalInputs(fixture.componentInstance, {
518 name: 'signal-input-required-test',
519 })
520β
521 fixture.detectChanges()
522 tick()
523β
524 expect(fixture.componentInstance.query.data()).toEqual(
525 'signal-input-required-test',
526 )
527 }))
528β
529 test('should run optionsFn in injection context', fakeAsync(async () => {
530 @Injectable()
531 class FakeService {
532 getData(name: string) {
533 return Promise.resolve(name)
534 }
535 }
536β
537 @Component({
538 selector: 'app-fake',
539 template: `{{ query.data() }}`,
540 standalone: true,
541 providers: [FakeService],
542 })
543 class FakeComponent {
544 name = signal<string>('test name')
545β
546 query = injectQuery(() => {
547 const service = inject(FakeService)
548β
549 return {
550 queryKey: ['fake', this.name()],
551 queryFn: () => {
552 return service.getData(this.name())
553 },
554 }
555 })
556 }
557β
558 const fixture = TestBed.createComponent(FakeComponent)
559 fixture.detectChanges()
560 tick()
561β
562 expect(fixture.componentInstance.query.data()).toEqual('test name')
563β
564 fixture.componentInstance.name.set('test name 2')
565 fixture.detectChanges()
566 tick()
567β
568 expect(fixture.componentInstance.query.data()).toEqual('test name 2')
569 }))
570β
571 test('should run optionsFn in injection context and allow passing injector to queryFn', fakeAsync(async () => {
572 @Injectable()
573 class FakeService {
574 getData(name: string) {
575 return Promise.resolve(name)
576 }
577 }
578β
579 @Component({
580 selector: 'app-fake',
581 template: `{{ query.data() }}`,
582 standalone: true,
583 providers: [FakeService],
584 })
585 class FakeComponent {
586 name = signal<string>('test name')
587β
588 query = injectQuery(() => {
589 const injector = inject(Injector)
590β
591 return {
592 queryKey: ['fake', this.name()],
593 queryFn: () => {
594 const service = injector.get(FakeService)
595 return service.getData(this.name())
596 },
597 }
598 })
599 }
600β
601 const fixture = TestBed.createComponent(FakeComponent)
602 fixture.detectChanges()
603 tick()
604β
605 expect(fixture.componentInstance.query.data()).toEqual('test name')
606β
607 fixture.componentInstance.name.set('test name 2')
608 fixture.detectChanges()
609 tick()
610β
611 expect(fixture.componentInstance.query.data()).toEqual('test name 2')
612 }))
613β
614 describe('injection context', () => {
615 test('throws NG0203 with descriptive error outside injection context', () => {
616 expect(() => {
617 injectQuery(() => ({
618 queryKey: ['injectionContextError'],
619 queryFn: simpleFetcher,
620 }))
621 }).toThrowError(/NG0203(.*?)injectQuery/)
622 })
623β
624 test('can be used outside injection context when passing an injector', () => {
625 const query = injectQuery(
626 () => ({
627 queryKey: ['manualInjector'],
628 queryFn: simpleFetcher,
629 }),
630 TestBed.inject(Injector),
631 )
632β
633 expect(query.status()).toBe('pending')
634 })
635 })
636})