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

inject-query.test.ts

564 lines16.8 KB

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