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

useQueryClient.test.ts

51 lines1.7 KB

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})