Open History to see the last commit
1import { beforeEach, describe, expect, it, vi } from 'vitest'
2import * as VueDemi from 'vue-demi'
3import { useQueryClient } from '../useQueryClient'
4import { VUE_QUERY_CLIENT } from '../utils'
5β
6vi.mock('vue-demi', async () => {
7 const actual = await vi.importActual<typeof VueDemi>('vue-demi')
8 return {
9 ...actual,
10 inject: vi.fn(),
11 hasInjectionContext: vi.fn(() => true),
12 }
13})
14β
15describe('useQueryClient', () => {
16 const injectSpy = vi.mocked(VueDemi.inject)
17 const hasInjectionContextSpy = vi.mocked(VueDemi.hasInjectionContext)
18β
19 beforeEach(() => {
20 vi.clearAllMocks()
21 })
22β
23 it('should return queryClient when it is provided in the context', () => {
24 const queryClientMock = { name: 'Mocked client' }
25 injectSpy.mockReturnValueOnce(queryClientMock)
26β
27 const queryClient = useQueryClient()
28β
29 expect(queryClient).toStrictEqual(queryClientMock)
30 expect(injectSpy).toHaveBeenCalledTimes(1)
31 expect(injectSpy).toHaveBeenCalledWith(VUE_QUERY_CLIENT)
32 })
33β
34 it('should throw an error when queryClient does not exist in the context', () => {
35 injectSpy.mockReturnValueOnce(undefined)
36β
37 expect(useQueryClient).toThrow(
38 "No 'queryClient' found in Vue context, use 'VueQueryPlugin' to properly initialize the library.",
39 )
40 expect(injectSpy).toHaveBeenCalledTimes(1)
41 expect(injectSpy).toHaveBeenCalledWith(VUE_QUERY_CLIENT)
42 })
43β
44 it('should throw an error when used outside of setup function', () => {
45 hasInjectionContextSpy.mockReturnValueOnce(false)
46β
47 expect(useQueryClient).toThrow(
48 'vue-query hooks can only be used inside setup() function or functions that support injection context.',
49 )
50 expect(hasInjectionContextSpy).toHaveBeenCalledTimes(1)
51 })
52β
53 it('should call inject with a custom key as a suffix', () => {
54 const queryClientKey = 'foo'
55 const expectedKeyParameter = `${VUE_QUERY_CLIENT}:${queryClientKey}`
56 const queryClientMock = { name: 'Mocked client' }
57 injectSpy.mockReturnValueOnce(queryClientMock)
58β
59 useQueryClient(queryClientKey)
60β
61 expect(injectSpy).toHaveBeenCalledWith(expectedKeyParameter)
62 })
63})