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

useQueryClient.test.ts

64 lines2.2 KB

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