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

useQuery.test.ts

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