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

vueQueryPlugin.test.ts

446 lines13.1 KB

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