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

useIsFetching.test.ts

79 lines2.2 KB

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