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

useQueryClient.test.ts

49 lines1.6 KB

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