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

vueQueryPlugin.test.ts

400 lines11.4 KB

1import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
2import { isVue2, isVue3, ref } from 'vue-demi'
3import { QueryClient } from '../queryClient'
4import { VueQueryPlugin } from '../vueQueryPlugin'
5import { VUE_QUERY_CLIENT } from '../utils'
6import { setupDevtools } from '../devtools/devtools'
7import { useQuery } from '../useQuery'
8import { useQueries } from '../useQueries'
9import type { App, ComponentOptions } from 'vue'
10import type { Mock } from 'vitest'
11​
12vi.mock('../devtools/devtools')
13vi.mock('../useQueryClient')
14vi.mock('../useBaseQuery')
15​
16type UnmountCallback = () => void
17​
18interface TestApp extends App {
19 onUnmount: UnmountCallback
20 _unmount: UnmountCallback
21 _mixin: ComponentOptions
22 _provided: Record<string, any>
23 $root: TestApp
25​
26const testIf = (condition: boolean) => (condition ? test : test.skip)
27​
28function getAppMock(withUnmountHook = false): TestApp {
29 const mock = {
30 provide: vi.fn(),
31 unmount: vi.fn(),
32 onUnmount: withUnmountHook
33 ? vi.fn((u: UnmountCallback) => {
34 mock._unmount = u
35 })
36 : undefined,
37 mixin: (m: ComponentOptions) => {
38 mock._mixin = m
39 },
40 } as unknown as TestApp
41​
42 return mock
44​
45describe('VueQueryPlugin', () => {
46 beforeEach(() => {
47 vi.useFakeTimers()
48 })
49​
50 afterEach(() => {
51 vi.useRealTimers()
52 })
53​
54 describe('devtools', () => {
55 test('should NOT setup devtools', () => {
56 const setupDevtoolsMock = setupDevtools as Mock
57 const appMock = getAppMock()
58 VueQueryPlugin.install(appMock)
59​
60 expect(setupDevtoolsMock).toHaveBeenCalledTimes(0)
61 })
62​
63 testIf(isVue2)('should NOT setup devtools by default', () => {
64 const envCopy = process.env.NODE_ENV
65 process.env.NODE_ENV = 'development'
66 const setupDevtoolsMock = setupDevtools as Mock
67 const appMock = getAppMock()
68 VueQueryPlugin.install(appMock)
69​
70 appMock.$root = appMock
71 appMock._mixin.beforeCreate?.call(appMock)
72 process.env.NODE_ENV = envCopy
73​
74 expect(setupDevtoolsMock).toHaveBeenCalledTimes(0)
75 })
76​
77 testIf(isVue2)('should setup devtools', () => {
78 const envCopy = process.env.NODE_ENV
79 process.env.NODE_ENV = 'development'
80 const setupDevtoolsMock = setupDevtools as Mock
81 const appMock = getAppMock()
82 VueQueryPlugin.install(appMock, { enableDevtoolsV6Plugin: true })
83​
84 appMock.$root = appMock
85 appMock._mixin.beforeCreate?.call(appMock)
86 process.env.NODE_ENV = envCopy
87​
88 expect(setupDevtoolsMock).toHaveBeenCalledTimes(1)
89 })
90​
91 testIf(isVue3)('should NOT setup devtools by default', () => {
92 const envCopy = process.env.NODE_ENV
93 process.env.NODE_ENV = 'development'
94 const setupDevtoolsMock = setupDevtools as Mock
95 const appMock = getAppMock()
96 VueQueryPlugin.install(appMock)
97 process.env.NODE_ENV = envCopy
98​
99 expect(setupDevtoolsMock).toHaveBeenCalledTimes(0)
100 })
101​
102 testIf(isVue3)('should setup devtools', () => {
103 const envCopy = process.env.NODE_ENV
104 process.env.NODE_ENV = 'development'
105 const setupDevtoolsMock = setupDevtools as Mock
106 const appMock = getAppMock()
107 VueQueryPlugin.install(appMock, { enableDevtoolsV6Plugin: true })
108 process.env.NODE_ENV = envCopy
109​
110 expect(setupDevtoolsMock).toHaveBeenCalledTimes(1)
111 })
112 })
113​
114 describe('when app unmounts', () => {
115 test('should call unmount on each client when onUnmount is missing', () => {
116 const appMock = getAppMock()
117 const customClient = {
118 mount: vi.fn(),
119 unmount: vi.fn(),
120 } as unknown as QueryClient
121 const originalUnmount = appMock.unmount
122 VueQueryPlugin.install(appMock, {
123 queryClient: customClient,
124 })
125​
126 appMock.unmount()
127​
128 expect(appMock.unmount).not.toEqual(originalUnmount)
129 expect(customClient.unmount).toHaveBeenCalledTimes(1)
130 expect(originalUnmount).toHaveBeenCalledTimes(1)
131 })
132​
133 test('should call onUnmount if present', () => {
134 const appMock = getAppMock(true)
135 const customClient = {
136 mount: vi.fn(),
137 unmount: vi.fn(),
138 } as unknown as QueryClient
139 const originalUnmount = appMock.unmount
140 VueQueryPlugin.install(appMock, { queryClient: customClient })
141​
142 appMock._unmount()
143​
144 expect(appMock.unmount).toEqual(originalUnmount)
145 expect(customClient.unmount).toHaveBeenCalledTimes(1)
146 })
147 })
148​
149 describe('when called without additional options', () => {
150 testIf(isVue2)('should provide a client with default clientKey', () => {
151 const appMock = getAppMock()
152 VueQueryPlugin.install(appMock)
153​
154 appMock._mixin.beforeCreate?.call(appMock)
155​
156 expect(appMock._provided).toMatchObject({
157 VUE_QUERY_CLIENT: expect.any(QueryClient),
158 })
159 })
160​
161 testIf(isVue3)('should provide a client with default clientKey', () => {
162 const appMock = getAppMock()
163 VueQueryPlugin.install(appMock)
164​
165 expect(appMock.provide).toHaveBeenCalledWith(
166 VUE_QUERY_CLIENT,
167 expect.any(QueryClient),
168 )
169 })
170 })
171​
172 describe('when called with custom clientKey', () => {
173 testIf(isVue2)('should provide a client with customized clientKey', () => {
174 const appMock = getAppMock()
175 VueQueryPlugin.install(appMock, { queryClientKey: 'CUSTOM' })
176​
177 appMock._mixin.beforeCreate?.call(appMock)
178​
179 expect(appMock._provided).toMatchObject({
180 [VUE_QUERY_CLIENT + ':CUSTOM']: expect.any(QueryClient),
181 })
182 })
183​
184 testIf(isVue3)('should provide a client with customized clientKey', () => {
185 const appMock = getAppMock()
186 VueQueryPlugin.install(appMock, { queryClientKey: 'CUSTOM' })
187​
188 expect(appMock.provide).toHaveBeenCalledWith(
189 VUE_QUERY_CLIENT + ':CUSTOM',
190 expect.any(QueryClient),
191 )
192 })
193 })
194​
195 describe('when called with custom client', () => {
196 testIf(isVue2)('should provide that custom client', () => {
197 const appMock = getAppMock()
198 const customClient = { mount: vi.fn() } as unknown as QueryClient
199 VueQueryPlugin.install(appMock, { queryClient: customClient })
200​
201 appMock._mixin.beforeCreate?.call(appMock)
202​
203 expect(customClient.mount).toHaveBeenCalled()
204 expect(appMock._provided).toMatchObject({
205 VUE_QUERY_CLIENT: customClient,
206 })
207 })
208​
209 testIf(isVue3)('should provide that custom client', () => {
210 const appMock = getAppMock()
211 const customClient = { mount: vi.fn() } as unknown as QueryClient
212 VueQueryPlugin.install(appMock, { queryClient: customClient })
213​
214 expect(customClient.mount).toHaveBeenCalled()
215 expect(appMock.provide).toHaveBeenCalledWith(
216 VUE_QUERY_CLIENT,
217 customClient,
218 )
219 })
220 })
221​
222 describe('when called with custom client config', () => {
223 testIf(isVue2)(
224 'should instantiate a client with the provided config',
225 () => {
226 const appMock = getAppMock()
227 const config = {
228 defaultOptions: { queries: { enabled: true } },
229 }
230 VueQueryPlugin.install(appMock, {
231 queryClientConfig: config,
232 })
233​
234 appMock._mixin.beforeCreate?.call(appMock)
235 const client = appMock._provided.VUE_QUERY_CLIENT as QueryClient
236 const defaultOptions = client.getDefaultOptions()
237​
238 expect(defaultOptions).toEqual(config.defaultOptions)
239 },
240 )
241​
242 testIf(isVue3)(
243 'should instantiate a client with the provided config',
244 () => {
245 const appMock = getAppMock()
246 const config = {
247 defaultOptions: { queries: { enabled: true } },
248 }
249 VueQueryPlugin.install(appMock, {
250 queryClientConfig: config,
251 })
252​
253 const client = (appMock.provide as Mock).mock.calls[0]?.[1]
254 const defaultOptions = client.getDefaultOptions()
255​
256 expect(defaultOptions).toEqual(config.defaultOptions)
257 },
258 )
259 })
260​
261 describe('when persister is provided', () => {
262 test('should properly modify isRestoring flag on queryClient', async () => {
263 const appMock = getAppMock()
264 const customClient = {
265 mount: vi.fn(),
266 isRestoring: ref(false),
267 } as unknown as QueryClient
268​
269 VueQueryPlugin.install(appMock, {
270 queryClient: customClient,
271 clientPersister: () => [
272 vi.fn(),
273 new Promise((resolve) => {
274 resolve()
275 }),
276 ],
277 })
278​
279 expect(customClient.isRestoring?.value).toBeTruthy()
280​
281 await vi.advanceTimersByTimeAsync(0)
282​
283 expect(customClient.isRestoring?.value).toBeFalsy()
284 })
285​
286 test('should delay useQuery subscription and not call fetcher if data is not stale', async () => {
287 const appMock = getAppMock()
288 const customClient = new QueryClient({
289 defaultOptions: {
290 queries: {
291 staleTime: 1000 * 60 * 60,
292 },
293 },
294 })
295​
296 VueQueryPlugin.install(appMock, {
297 queryClient: customClient,
298 clientPersister: (client) => [
299 vi.fn(),
300 new Promise((resolve) => {
301 setTimeout(() => {
302 client.setQueryData(['persist'], () => ({
303 foo: 'bar',
304 }))
305 resolve()
306 }, 0)
307 }),
308 ],
309 })
310​
311 const fnSpy = vi.fn()
312​
313 const query = useQuery(
314 {
315 queryKey: ['persist'],
316 queryFn: fnSpy,
317 },
318 customClient,
319 )
320​
321 expect(customClient.isRestoring?.value).toBeTruthy()
322 expect(query.isFetching.value).toBeFalsy()
323 expect(query.data.value).toStrictEqual(undefined)
324 expect(fnSpy).toHaveBeenCalledTimes(0)
325​
326 await vi.advanceTimersByTimeAsync(0)
327​
328 expect(customClient.isRestoring?.value).toBeFalsy()
329 expect(query.data.value).toStrictEqual({ foo: 'bar' })
330 expect(fnSpy).toHaveBeenCalledTimes(0)
331 })
332​
333 test('should delay useQueries subscription and not call fetcher if data is not stale', async () => {
334 const appMock = getAppMock()
335 const customClient = new QueryClient({
336 defaultOptions: {
337 queries: {
338 staleTime: 1000 * 60 * 60,
339 },
340 },
341 })
342​
343 VueQueryPlugin.install(appMock, {
344 queryClient: customClient,
345 clientPersister: (client) => [
346 vi.fn(),
347 new Promise((resolve) => {
348 setTimeout(() => {
349 client.setQueryData(['persist1'], () => ({
350 foo1: 'bar1',
351 }))
352 client.setQueryData(['persist2'], () => ({
353 foo2: 'bar2',
354 }))
355 resolve()
356 }, 0)
357 }),
358 ],
359 })
360​
361 const fnSpy = vi.fn()
362​
363 const query = useQuery(
364 {
365 queryKey: ['persist1'],
366 queryFn: fnSpy,
367 },
368 customClient,
369 )
370​
371 const queries = useQueries(
372 {
373 queries: [
374 {
375 queryKey: ['persist2'],
376 queryFn: fnSpy,
377 },
378 ],
379 },
380 customClient,
381 )
382​
383 expect(customClient.isRestoring?.value).toBeTruthy()
384​
385 expect(query.isFetching.value).toBeFalsy()
386 expect(query.data.value).toStrictEqual(undefined)
387​
388 expect(queries.value[0].isFetching).toBeFalsy()
389 expect(queries.value[0].data).toStrictEqual(undefined)
390 expect(fnSpy).toHaveBeenCalledTimes(0)
391​
392 await vi.advanceTimersByTimeAsync(0)
393​
394 expect(customClient.isRestoring?.value).toBeFalsy()
395 expect(query.data.value).toStrictEqual({ foo1: 'bar1' })
396 expect(queries.value[0].data).toStrictEqual({ foo2: 'bar2' })
397 expect(fnSpy).toHaveBeenCalledTimes(0)
398 })
399 })
400})