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

vueQueryPlugin.test.ts

487 lines14.6 KB

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