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