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

useQuery.test.ts

331 lines8.3 KB

1import {
2 computed,
3 reactive,
4 ref,
5 onScopeDispose,
6 getCurrentInstance,
7} from 'vue-demi'
8import { QueryObserver } from '@tanstack/query-core'
9​
10import {
11 flushPromises,
12 rejectFetcher,
13 simpleFetcher,
14 getSimpleFetcherWithReturnData,
15} from './test-utils'
16import { useQuery } from '../useQuery'
17import { parseQueryArgs, useBaseQuery } from '../useBaseQuery'
18​
19jest.mock('../useQueryClient')
20jest.mock('../useBaseQuery')
21​
22describe('useQuery', () => {
23 test('should properly execute query', () => {
24 useQuery(['key0'], simpleFetcher, { staleTime: 1000 })
25​
26 expect(useBaseQuery).toBeCalledWith(
27 QueryObserver,
28 ['key0'],
29 simpleFetcher,
30 {
31 staleTime: 1000,
32 },
33 )
34 })
35​
36 test('should return loading status initially', () => {
37 const query = useQuery(['key1'], simpleFetcher)
38​
39 expect(query).toMatchObject({
40 status: { value: 'loading' },
41 isLoading: { value: true },
42 isFetching: { value: true },
43 isStale: { value: true },
44 })
45 })
46​
47 test('should resolve to success and update reactive state: useQuery(key, dataFn)', async () => {
48 const query = useQuery(['key2'], getSimpleFetcherWithReturnData('result2'))
49​
50 await flushPromises()
51​
52 expect(query).toMatchObject({
53 status: { value: 'success' },
54 data: { value: 'result2' },
55 isLoading: { value: false },
56 isFetching: { value: false },
57 isFetched: { value: true },
58 isSuccess: { value: true },
59 })
60 })
61​
62 test('should resolve to success and update reactive state: useQuery(optionsObj)', async () => {
63 const query = useQuery({
64 queryKey: ['key31'],
65 queryFn: getSimpleFetcherWithReturnData('result31'),
66 enabled: true,
67 })
68​
69 await flushPromises()
70​
71 expect(query).toMatchObject({
72 status: { value: 'success' },
73 data: { value: 'result31' },
74 isLoading: { value: false },
75 isFetching: { value: false },
76 isFetched: { value: true },
77 isSuccess: { value: true },
78 })
79 })
80​
81 test('should resolve to success and update reactive state: useQuery(key, optionsObj)', async () => {
82 const query = useQuery(['key32'], {
83 queryFn: getSimpleFetcherWithReturnData('result32'),
84 enabled: true,
85 })
86​
87 await flushPromises()
88​
89 expect(query).toMatchObject({
90 status: { value: 'success' },
91 data: { value: 'result32' },
92 isLoading: { value: false },
93 isFetching: { value: false },
94 isFetched: { value: true },
95 isSuccess: { value: true },
96 })
97 })
98​
99 test('should reject and update reactive state', async () => {
100 const query = useQuery(['key3'], rejectFetcher)
101​
102 await flushPromises()
103​
104 expect(query).toMatchObject({
105 status: { value: 'error' },
106 data: { value: undefined },
107 error: { value: { message: 'Some error' } },
108 isLoading: { value: false },
109 isFetching: { value: false },
110 isFetched: { value: true },
111 isError: { value: true },
112 failureCount: { value: 1 },
113 failureReason: { value: { message: 'Some error' } },
114 })
115 })
116​
117 test('should update query on reactive options object change', async () => {
118 const spy = jest.fn()
119 const onSuccess = ref(() => {
120 // Noop
121 })
122 useQuery(
123 ['key6'],
124 simpleFetcher,
125 reactive({
126 onSuccess,
127 staleTime: 1000,
128 }),
129 )
130​
131 onSuccess.value = spy
132​
133 await flushPromises()
134​
135 expect(spy).toBeCalledTimes(1)
136 })
137​
138 test('should update query on reactive (Ref) key change', async () => {
139 const secondKeyRef = ref('key7')
140 const query = useQuery(['key6', secondKeyRef], simpleFetcher)
141​
142 await flushPromises()
143​
144 expect(query).toMatchObject({
145 status: { value: 'success' },
146 })
147​
148 secondKeyRef.value = 'key8'
149 await flushPromises()
150​
151 expect(query).toMatchObject({
152 status: { value: 'loading' },
153 data: { value: undefined },
154 })
155​
156 await flushPromises()
157​
158 expect(query).toMatchObject({
159 status: { value: 'success' },
160 })
161 })
162​
163 test("should update query when an option is passed as Ref and it's changed", async () => {
164 const enabled = ref(false)
165 const query = useQuery(['key9'], simpleFetcher, { enabled })
166​
167 await flushPromises()
168​
169 expect(query).toMatchObject({
170 fetchStatus: { value: 'idle' },
171 data: { value: undefined },
172 })
173​
174 enabled.value = true
175​
176 await flushPromises()
177​
178 expect(query).toMatchObject({
179 fetchStatus: { value: 'fetching' },
180 data: { value: undefined },
181 })
182​
183 await flushPromises()
184​
185 expect(query).toMatchObject({
186 status: { value: 'success' },
187 })
188 })
189​
190 test('should properly execute dependant queries', async () => {
191 const { data } = useQuery(['dependant1'], simpleFetcher)
192​
193 const enabled = computed(() => !!data.value)
194​
195 const { fetchStatus, status } = useQuery(
196 ['dependant2'],
197 simpleFetcher,
198 reactive({
199 enabled,
200 }),
201 )
202​
203 expect(data.value).toStrictEqual(undefined)
204 expect(fetchStatus.value).toStrictEqual('idle')
205​
206 await flushPromises()
207​
208 expect(data.value).toStrictEqual('Some data')
209 expect(fetchStatus.value).toStrictEqual('fetching')
210​
211 await flushPromises()
212​
213 expect(fetchStatus.value).toStrictEqual('idle')
214 expect(status.value).toStrictEqual('success')
215 })
216​
217 test('should stop listening to changes on onScopeDispose', async () => {
218 const onScopeDisposeMock = onScopeDispose as jest.MockedFunction<
219 typeof onScopeDispose
220 >
221 onScopeDisposeMock.mockImplementationOnce((fn) => fn())
222​
223 const { status } = useQuery(['onScopeDispose'], simpleFetcher)
224​
225 expect(status.value).toStrictEqual('loading')
226​
227 await flushPromises()
228​
229 expect(status.value).toStrictEqual('loading')
230​
231 await flushPromises()
232​
233 expect(status.value).toStrictEqual('loading')
234 })
235​
236 describe('parseQueryArgs', () => {
237 test('should unwrap refs arguments', () => {
238 const key = ref(['key'])
239 const fn = ref(simpleFetcher)
240 const options = ref({ enabled: ref(true) })
241​
242 const result = parseQueryArgs(key, fn, options)
243 const expected = {
244 queryKey: ['key'],
245 queryFn: simpleFetcher,
246 enabled: true,
247 }
248​
249 expect(result).toEqual(expected)
250 })
251​
252 test('should unwrap refs with fn in options', () => {
253 const key = ref(['key'])
254 const fn = ref(simpleFetcher)
255 const options = ref({ queryFn: fn, enabled: ref(true) })
256​
257 const result = parseQueryArgs(key, options)
258 const expected = {
259 queryKey: ['key'],
260 queryFn: simpleFetcher,
261 enabled: true,
262 }
263​
264 expect(result).toEqual(expected)
265 })
266​
267 test('should unwrap refs in options', () => {
268 const key = ref(['key'])
269 const fn = ref(simpleFetcher)
270 const options = ref({ queryKey: key, queryFn: fn, enabled: ref(true) })
271​
272 const result = parseQueryArgs(options)
273 const expected = {
274 queryKey: ['key'],
275 queryFn: simpleFetcher,
276 enabled: true,
277 }
278​
279 expect(result).toEqual(expected)
280 })
281 })
282​
283 describe('suspense', () => {
284 test('should return a Promise', () => {
285 const getCurrentInstanceSpy = getCurrentInstance as jest.Mock
286 getCurrentInstanceSpy.mockImplementation(() => ({ suspense: {} }))
287​
288 const query = useQuery(['suspense'], simpleFetcher)
289 const result = query.suspense()
290​
291 expect(result).toBeInstanceOf(Promise)
292 })
293​
294 test('should resolve after being enabled', () => {
295 const getCurrentInstanceSpy = getCurrentInstance as jest.Mock
296 getCurrentInstanceSpy.mockImplementation(() => ({ suspense: {} }))
297​
298 let afterTimeout = false
299 const isEnabeld = ref(false)
300 const query = useQuery(['suspense'], simpleFetcher, {
301 enabled: isEnabeld,
302 })
303​
304 setTimeout(() => {
305 afterTimeout = true
306 isEnabeld.value = true
307 }, 200)
308​
309 return query.suspense().then(() => {
310 expect(afterTimeout).toBe(true)
311 })
312 })
313​
314 test('should resolve immidiately when stale without refetching', () => {
315 const getCurrentInstanceSpy = getCurrentInstance as jest.Mock
316 getCurrentInstanceSpy.mockImplementation(() => ({ suspense: {} }))
317​
318 const fetcherSpy = jest.fn(() => simpleFetcher())
319​
320 // let afterTimeout = false;
321 const query = useQuery(['suspense'], simpleFetcher, {
322 staleTime: 10000,
323 initialData: 'foo',
324 })
325​
326 return query.suspense().then(() => {
327 expect(fetcherSpy).toHaveBeenCalledTimes(0)
328 })
329 })
330 })
331})