Open History to see the last commit
1import { beforeEach, describe, expect, test, 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 test('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 test('should throw an error when queryClient does not exist in the context', () => {
35 injectSpy.mockReturnValueOnce(undefined)
36β
37 expect(useQueryClient).toThrowError()
38 expect(injectSpy).toHaveBeenCalledTimes(1)
39 expect(injectSpy).toHaveBeenCalledWith(VUE_QUERY_CLIENT)
40 })
41β
42 test('should throw an error when used outside of setup function', () => {
43 hasInjectionContextSpy.mockReturnValueOnce(false)
44β
45 expect(useQueryClient).toThrowError()
46 expect(hasInjectionContextSpy).toHaveBeenCalledTimes(1)
47 })
48β
49 test('should call inject with a custom key as a suffix', () => {
50 const queryClientKey = 'foo'
51 const expectedKeyParameter = `${VUE_QUERY_CLIENT}:${queryClientKey}`
52 const queryClientMock = { name: 'Mocked client' }
53 injectSpy.mockReturnValueOnce(queryClientMock)
54β
55 useQueryClient(queryClientKey)
56β
57 expect(injectSpy).toHaveBeenCalledWith(expectedKeyParameter)
58 })
59})