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

vueQueryPlugin.test.ts

384 lines10.9 KB

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