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

vueQueryPlugin.test.ts

461 lines13.7 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 call the unmount returned by clientPersister when the app unmounts', () => {
332 const appMock = getAppMock(true)
333 const customClient = new QueryClient()
334 const persisterUnmount = vi.fn<() => void>()
335​
336 VueQueryPlugin.install(appMock, {
337 queryClient: customClient,
338 clientPersister: () => [persisterUnmount, sleep(10)],
339 })
340​
341 expect(persisterUnmount).not.toHaveBeenCalled()
342​
343 appMock._unmount()
344​
345 expect(persisterUnmount).toHaveBeenCalledTimes(1)
346 })
347​
348 it('should delay useQuery subscription and not call fetcher if data is not stale', async () => {
349 const key = createKey()
350 const appMock = getAppMock()
351 const customClient = new QueryClient({
352 defaultOptions: {
353 queries: {
354 staleTime: 60 * 60 * 1000,
355 },
356 },
357 })
358​
359 VueQueryPlugin.install(appMock, {
360 queryClient: customClient,
361 clientPersister: (client) => [
362 vi.fn<() => void>(),
363 new Promise((resolve) => {
364 setTimeout(() => {
365 client.setQueryData(key, () => ({
366 foo: 'bar',
367 }))
368 resolve()
369 }, 0)
370 }),
371 ],
372 })
373​
374 const queryFn = vi.fn<() => { foo: string }>()
375​
376 const query = useQuery(
377 {
378 queryKey: key,
379 queryFn,
380 },
381 customClient,
382 )
383​
384 expect(customClient.isRestoring?.value).toBe(true)
385 expect(query.isFetching.value).toBe(false)
386 expect(query.data.value).toBeUndefined()
387 expect(queryFn).toHaveBeenCalledTimes(0)
388 await vi.advanceTimersByTimeAsync(0)
389 expect(customClient.isRestoring?.value).toBe(false)
390 expect(query.data.value).toStrictEqual({ foo: 'bar' })
391 expect(queryFn).toHaveBeenCalledTimes(0)
392 })
393​
394 it('should delay useQueries subscription and not call fetcher if data is not stale', async () => {
395 const key1 = createKey()
396 const key2 = createKey()
397 const appMock = getAppMock()
398 const customClient = new QueryClient({
399 defaultOptions: {
400 queries: {
401 staleTime: 60 * 60 * 1000,
402 },
403 },
404 })
405​
406 VueQueryPlugin.install(appMock, {
407 queryClient: customClient,
408 clientPersister: (client) => [
409 vi.fn<() => void>(),
410 new Promise((resolve) => {
411 setTimeout(() => {
412 client.setQueryData(key1, () => ({
413 foo1: 'bar1',
414 }))
415 client.setQueryData(key2, () => ({
416 foo2: 'bar2',
417 }))
418 resolve()
419 }, 0)
420 }),
421 ],
422 })
423​
424 const queryFn = vi.fn<() => Record<string, string>>()
425​
426 const query = useQuery(
427 {
428 queryKey: key1,
429 queryFn,
430 },
431 customClient,
432 )
433​
434 const queries = useQueries(
435 {
436 queries: [
437 {
438 queryKey: key2,
439 queryFn,
440 },
441 ],
442 },
443 customClient,
444 )
445​
446 expect(customClient.isRestoring?.value).toBe(true)
447​
448 expect(query.isFetching.value).toBe(false)
449 expect(query.data.value).toBeUndefined()
450​
451 expect(queries.value[0].isFetching).toBe(false)
452 expect(queries.value[0].data).toBeUndefined()
453 expect(queryFn).toHaveBeenCalledTimes(0)
454 await vi.advanceTimersByTimeAsync(0)
455 expect(customClient.isRestoring?.value).toBe(false)
456 expect(query.data.value).toStrictEqual({ foo1: 'bar1' })
457 expect(queries.value[0].data).toStrictEqual({ foo2: 'bar2' })
458 expect(queryFn).toHaveBeenCalledTimes(0)
459 })
460 })
461})