Open History to see the last commit
1import { beforeEach, describe, expect, test, vi } from 'vitest'
2import { hasInjectionContext, inject } from 'vue-demi'
3import { useQueryClient } from '../useQueryClient'
4import { VUE_QUERY_CLIENT } from '../utils'
5import type { Mock } from 'vitest'
6β
7describe('useQueryClient', () => {
8 const injectSpy = inject as Mock
9 const hasInjectionContextSpy = hasInjectionContext as Mock
10β
11 beforeEach(() => {
12 vi.restoreAllMocks()
13 })
14β
15 test('should return queryClient when it is provided in the context', () => {
16 const queryClientMock = { name: 'Mocked client' }
17 injectSpy.mockReturnValueOnce(queryClientMock)
18β
19 const queryClient = useQueryClient()
20β
21 expect(queryClient).toStrictEqual(queryClientMock)
22 expect(injectSpy).toHaveBeenCalledTimes(1)
23 expect(injectSpy).toHaveBeenCalledWith(VUE_QUERY_CLIENT)
24 })
25β
26 test('should throw an error when queryClient does not exist in the context', () => {
27 injectSpy.mockReturnValueOnce(undefined)
28β
29 expect(useQueryClient).toThrowError()
30 expect(injectSpy).toHaveBeenCalledTimes(1)
31 expect(injectSpy).toHaveBeenCalledWith(VUE_QUERY_CLIENT)
32 })
33β
34 test('should throw an error when used outside of setup function', () => {
35 hasInjectionContextSpy.mockReturnValueOnce(false)
36β
37 expect(useQueryClient).toThrowError()
38 expect(hasInjectionContextSpy).toHaveBeenCalledTimes(1)
39 })
40β
41 test('should call inject with a custom key as a suffix', () => {
42 const queryClientKey = 'foo'
43 const expectedKeyParameter = `${VUE_QUERY_CLIENT}:${queryClientKey}`
44 const queryClientMock = { name: 'Mocked client' }
45 injectSpy.mockReturnValueOnce(queryClientMock)
46β
47 useQueryClient(queryClientKey)
48β
49 expect(injectSpy).toHaveBeenCalledWith(expectedKeyParameter)
50 })
51})