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

useIsFetching.test.ts

76 lines2.1 KB

1import { describe, expect, test, vi } from 'vitest'
2import { onScopeDispose, reactive } from 'vue-demi'
3import { useQuery } from '../useQuery'
4import { useIsFetching } from '../useIsFetching'
5import { flushPromises, simpleFetcher } from './test-utils'
6import type { MockedFunction } from 'vitest'
7​
8vi.mock('../useQueryClient')
9​
10describe('useIsFetching', () => {
11 test('should properly return isFetching state', async () => {
12 const { isFetching: isFetchingQuery } = useQuery({
13 queryKey: ['isFetching1'],
14 queryFn: simpleFetcher,
15 })
16 useQuery({ queryKey: ['isFetching2'], queryFn: simpleFetcher })
17 const isFetching = useIsFetching()
18​
19 expect(isFetchingQuery.value).toStrictEqual(true)
20 expect(isFetching.value).toStrictEqual(2)
21​
22 await flushPromises()
23​
24 expect(isFetchingQuery.value).toStrictEqual(false)
25 expect(isFetching.value).toStrictEqual(0)
26 })
27​
28 test('should stop listening to changes on onScopeDispose', async () => {
29 const onScopeDisposeMock = onScopeDispose as MockedFunction<
30 typeof onScopeDispose
31 >
32 onScopeDisposeMock.mockImplementation((fn) => fn())
33​
34 const { status } = useQuery({
35 queryKey: ['onScopeDispose'],
36 queryFn: simpleFetcher,
37 })
38 const isFetching = useIsFetching()
39​
40 expect(status.value).toStrictEqual('pending')
41 expect(isFetching.value).toStrictEqual(1)
42​
43 await flushPromises()
44​
45 expect(status.value).toStrictEqual('pending')
46 expect(isFetching.value).toStrictEqual(1)
47​
48 await flushPromises()
49​
50 expect(status.value).toStrictEqual('pending')
51 expect(isFetching.value).toStrictEqual(1)
52​
53 onScopeDisposeMock.mockReset()
54 })
55​
56 test('should properly update filters', async () => {
57 const filter = reactive({ stale: false })
58 useQuery({
59 queryKey: ['isFetching'],
60 queryFn: () =>
61 new Promise((resolve) => {
62 setTimeout(() => {
63 return resolve('Some data')
64 }, 100)
65 }),
66 })
67 const isFetching = useIsFetching(filter)
68​
69 expect(isFetching.value).toStrictEqual(0)
70​
71 filter.stale = true
72 await flushPromises()
73​
74 expect(isFetching.value).toStrictEqual(1)
75 })
76})