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

useIsFetching.test.ts

101 lines2.7 KB

1import { onScopeDispose, reactive, ref } from 'vue-demi'
2​
3import { flushPromises, simpleFetcher } from './test-utils'
4import { useQuery } from '../useQuery'
5import { parseFilterArgs, useIsFetching } from '../useIsFetching'
6​
7jest.mock('../useQueryClient')
8​
9describe('useIsFetching', () => {
10 test('should properly return isFetching state', async () => {
11 const { isFetching: isFetchingQuery } = useQuery(
12 ['isFetching1'],
13 simpleFetcher,
14 )
15 useQuery(['isFetching2'], simpleFetcher)
16 const isFetching = useIsFetching()
17​
18 expect(isFetchingQuery.value).toStrictEqual(true)
19 expect(isFetching.value).toStrictEqual(2)
20​
21 await flushPromises()
22​
23 expect(isFetchingQuery.value).toStrictEqual(false)
24 expect(isFetching.value).toStrictEqual(0)
25 })
26​
27 test('should stop listening to changes on onScopeDispose', async () => {
28 const onScopeDisposeMock = onScopeDispose as jest.MockedFunction<
29 typeof onScopeDispose
30 >
31 onScopeDisposeMock.mockImplementation((fn) => fn())
32​
33 const { status } = useQuery(['onScopeDispose'], simpleFetcher)
34 const isFetching = useIsFetching()
35​
36 expect(status.value).toStrictEqual('loading')
37 expect(isFetching.value).toStrictEqual(1)
38​
39 await flushPromises()
40​
41 expect(status.value).toStrictEqual('loading')
42 expect(isFetching.value).toStrictEqual(1)
43​
44 await flushPromises()
45​
46 expect(status.value).toStrictEqual('loading')
47 expect(isFetching.value).toStrictEqual(1)
48​
49 onScopeDisposeMock.mockReset()
50 })
51​
52 test('should properly update filters', async () => {
53 const filter = reactive({ stale: false })
54 useQuery(
55 ['isFetching'],
56 () =>
57 new Promise((resolve) => {
58 setTimeout(() => {
59 return resolve('Some data')
60 }, 100)
61 }),
62 )
63 const isFetching = useIsFetching(filter)
64​
65 expect(isFetching.value).toStrictEqual(0)
66​
67 filter.stale = true
68 await flushPromises()
69​
70 expect(isFetching.value).toStrictEqual(1)
71​
72 await flushPromises(100)
73 })
74​
75 describe('parseFilterArgs', () => {
76 test('should default to empty filters', () => {
77 const result = parseFilterArgs(undefined)
78​
79 expect(result).toEqual({})
80 })
81​
82 test('should merge query key with filters', () => {
83 const filters = { stale: true }
84​
85 const result = parseFilterArgs(['key'], filters)
86 const expected = { ...filters, queryKey: ['key'] }
87​
88 expect(result).toEqual(expected)
89 })
90​
91 test('should unwrap refs arguments', () => {
92 const key = ref(['key'])
93 const filters = ref({ stale: ref(true) })
94​
95 const result = parseFilterArgs(key, filters)
96 const expected = { queryKey: ['key'], stale: true }
97​
98 expect(result).toEqual(expected)
99 })
100 })
101})