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

inject-query.test.ts

300 lines7.8 KB

1import { Component, computed, input, signal } from '@angular/core'
2import { TestBed, fakeAsync, flush, tick } from '@angular/core/testing'
3import { QueryClient } from '@tanstack/query-core'
4import { describe, expect, vi } from 'vitest'
5import { injectQuery } from '../inject-query'
6import { provideAngularQuery } from '../providers'
7import {
8 delayedFetcher,
9 getSimpleFetcherWithReturnData,
10 rejectFetcher,
11 setSignalInputs,
12 simpleFetcher,
13} from './test-utils'
14​
15describe('injectQuery', () => {
16 beforeEach(() => {
17 TestBed.configureTestingModule({
18 providers: [provideAngularQuery(new QueryClient())],
19 })
20 })
21​
22 test('should return pending status initially', fakeAsync(() => {
23 const query = TestBed.runInInjectionContext(() => {
24 return injectQuery(() => ({
25 queryKey: ['key1'],
26 queryFn: simpleFetcher,
27 }))
28 })
29​
30 expect(query.status()).toBe('pending')
31 expect(query.isPending()).toBe(true)
32 expect(query.isFetching()).toBe(true)
33 expect(query.isStale()).toBe(true)
34 expect(query.isFetched()).toBe(false)
35​
36 flush()
37 }))
38​
39 test('should resolve to success and update signal: injectQuery()', fakeAsync(() => {
40 const query = TestBed.runInInjectionContext(() => {
41 return injectQuery(() => ({
42 queryKey: ['key2'],
43 queryFn: getSimpleFetcherWithReturnData('result2'),
44 }))
45 })
46​
47 flush()
48​
49 expect(query.status()).toBe('success')
50 expect(query.data()).toBe('result2')
51 expect(query.isPending()).toBe(false)
52 expect(query.isFetching()).toBe(false)
53 expect(query.isFetched()).toBe(true)
54 expect(query.isSuccess()).toBe(true)
55 }))
56​
57 test('should reject and update signal', fakeAsync(() => {
58 const query = TestBed.runInInjectionContext(() => {
59 return injectQuery(() => ({
60 retry: false,
61 queryKey: ['key3'],
62 queryFn: rejectFetcher,
63 }))
64 })
65​
66 flush()
67​
68 expect(query.status()).toBe('error')
69 expect(query.data()).toBe(undefined)
70 expect(query.error()).toMatchObject({ message: 'Some error' })
71 expect(query.isPending()).toBe(false)
72 expect(query.isFetching()).toBe(false)
73 expect(query.isError()).toBe(true)
74 expect(query.failureCount()).toBe(1)
75 expect(query.failureReason()).toMatchObject({ message: 'Some error' })
76 }))
77​
78 test('should update query on options contained signal change', fakeAsync(() => {
79 const key = signal(['key6', 'key7'])
80 const spy = vi.fn(simpleFetcher)
81​
82 const query = TestBed.runInInjectionContext(() => {
83 return injectQuery(() => ({
84 queryKey: key(),
85 queryFn: spy,
86 }))
87 })
88 flush()
89 expect(spy).toHaveBeenCalledTimes(1)
90​
91 expect(query.status()).toBe('success')
92​
93 key.set(['key8'])
94 TestBed.flushEffects()
95​
96 expect(spy).toHaveBeenCalledTimes(2)
97​
98 flush()
99 }))
100​
101 test('should only run query once enabled signal is set to true', fakeAsync(() => {
102 const spy = vi.fn(simpleFetcher)
103 const enabled = signal(false)
104​
105 const query = TestBed.runInInjectionContext(() => {
106 return injectQuery(() => ({
107 queryKey: ['key9'],
108 queryFn: spy,
109 enabled: enabled(),
110 }))
111 })
112​
113 expect(spy).not.toHaveBeenCalled()
114 expect(query.status()).toBe('pending')
115​
116 enabled.set(true)
117 TestBed.flushEffects()
118 flush()
119 expect(spy).toHaveBeenCalledTimes(1)
120 expect(query.status()).toBe('success')
121 }))
122​
123 test('should properly execute dependant queries', fakeAsync(() => {
124 const query1 = TestBed.runInInjectionContext(() => {
125 return injectQuery(() => ({
126 queryKey: ['dependant1'],
127 queryFn: simpleFetcher,
128 }))
129 })
130​
131 const dependentQueryFn = vi.fn().mockImplementation(delayedFetcher(1000))
132​
133 const query2 = TestBed.runInInjectionContext(() => {
134 return injectQuery(
135 computed(() => ({
136 queryKey: ['dependant2'],
137 queryFn: dependentQueryFn,
138 enabled: !!query1.data(),
139 })),
140 )
141 })
142​
143 expect(query1.data()).toStrictEqual(undefined)
144 expect(query2.fetchStatus()).toStrictEqual('idle')
145 expect(dependentQueryFn).not.toHaveBeenCalled()
146​
147 tick()
148 TestBed.flushEffects()
149​
150 expect(query1.data()).toStrictEqual('Some data')
151 expect(query2.fetchStatus()).toStrictEqual('fetching')
152​
153 flush()
154​
155 expect(query2.fetchStatus()).toStrictEqual('idle')
156 expect(query2.status()).toStrictEqual('success')
157 expect(dependentQueryFn).toHaveBeenCalledTimes(1)
158 expect(dependentQueryFn).toHaveBeenCalledWith(
159 expect.objectContaining({ queryKey: ['dependant2'] }),
160 )
161 }))
162​
163 test('should use the current value for the queryKey when refetch is called', fakeAsync(() => {
164 const fetchFn = vi.fn(simpleFetcher)
165 const keySignal = signal('key11')
166​
167 const query = TestBed.runInInjectionContext(() => {
168 return injectQuery(() => ({
169 queryKey: ['key10', keySignal()],
170 queryFn: fetchFn,
171 enabled: false,
172 }))
173 })
174​
175 expect(fetchFn).not.toHaveBeenCalled()
176​
177 query.refetch().then(() => {
178 expect(fetchFn).toHaveBeenCalledTimes(1)
179 expect(fetchFn).toHaveBeenCalledWith(
180 expect.objectContaining({
181 queryKey: ['key10', 'key11'],
182 }),
183 )
184 })
185​
186 flush()
187​
188 keySignal.set('key12')
189​
190 TestBed.flushEffects()
191​
192 query.refetch().then(() => {
193 expect(fetchFn).toHaveBeenCalledTimes(2)
194 expect(fetchFn).toHaveBeenCalledWith(
195 expect.objectContaining({
196 queryKey: ['key10', 'key12'],
197 }),
198 )
199 })
200​
201 flush()
202 }))
203​
204 describe('throwOnError', () => {
205 test('should evaluate throwOnError when query is expected to throw', fakeAsync(() => {
206 const boundaryFn = vi.fn()
207 TestBed.runInInjectionContext(() => {
208 return injectQuery(() => ({
209 queryKey: ['key12'],
210 queryFn: rejectFetcher,
211 throwOnError: boundaryFn,
212 }))
213 })
214​
215 flush()
216​
217 expect(boundaryFn).toHaveBeenCalledTimes(1)
218 expect(boundaryFn).toHaveBeenCalledWith(
219 Error('Some error'),
220 expect.objectContaining({
221 state: expect.objectContaining({ status: 'error' }),
222 }),
223 )
224 }))
225​
226 test('should throw when throwOnError is true', fakeAsync(() => {
227 TestBed.runInInjectionContext(() => {
228 return injectQuery(() => ({
229 queryKey: ['key13'],
230 queryFn: rejectFetcher,
231 throwOnError: true,
232 }))
233 })
234​
235 expect(() => {
236 flush()
237 }).toThrowError('Some error')
238 flush()
239 }))
240​
241 test('should throw when throwOnError function returns true', fakeAsync(() => {
242 TestBed.runInInjectionContext(() => {
243 return injectQuery(() => ({
244 queryKey: ['key14'],
245 queryFn: rejectFetcher,
246 throwOnError: () => true,
247 }))
248 })
249​
250 expect(() => {
251 flush()
252 }).toThrowError('Some error')
253 flush()
254 }))
255 })
256​
257 test('should set state to error when queryFn returns reject promise', fakeAsync(() => {
258 const query = TestBed.runInInjectionContext(() => {
259 return injectQuery(() => ({
260 retry: false,
261 queryKey: ['key15'],
262 queryFn: rejectFetcher,
263 }))
264 })
265​
266 expect(query.status()).toBe('pending')
267​
268 flush()
269​
270 expect(query.status()).toBe('error')
271 }))
272​
273 test('should render with required signal inputs', fakeAsync(async () => {
274 @Component({
275 selector: 'app-fake',
276 template: `{{ query.data() }}`,
277 standalone: true,
278 })
279 class FakeComponent {
280 name = input.required<string>()
281​
282 query = injectQuery(() => ({
283 queryKey: ['fake', this.name()],
284 queryFn: () => Promise.resolve(this.name()),
285 }))
286 }
287​
288 const fixture = TestBed.createComponent(FakeComponent)
289 setSignalInputs(fixture.componentInstance, {
290 name: 'signal-input-required-test',
291 })
292​
293 flush()
294 fixture.detectChanges()
295​
296 expect(fixture.debugElement.nativeElement.textContent).toEqual(
297 'signal-input-required-test',
298 )
299 }))
300})