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

inject-is-fetching.test.ts

63 lines1.7 KB

1import { TestBed } from '@angular/core/testing'
2import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
3import { Injector, provideZonelessChangeDetection } from '@angular/core'
4import { queryKey, sleep } from '@tanstack/query-test-utils'
5import {
6 QueryClient,
7 injectIsFetching,
8 injectQuery,
9 provideTanStackQuery,
10} from '..'
11​
12describe('injectIsFetching', () => {
13 let queryClient: QueryClient
14​
15 beforeEach(() => {
16 vi.useFakeTimers()
17 queryClient = new QueryClient()
18​
19 TestBed.configureTestingModule({
20 providers: [
21 provideZonelessChangeDetection(),
22 provideTanStackQuery(queryClient),
23 ],
24 })
25 })
26​
27 afterEach(() => {
28 vi.useRealTimers()
29 })
30​
31 test('Returns number of fetching queries', async () => {
32 const key = queryKey()
33 const isFetching = TestBed.runInInjectionContext(() => {
34 injectQuery(() => ({
35 queryKey: key,
36 queryFn: () => sleep(100).then(() => 'Some data'),
37 }))
38 return injectIsFetching()
39 })
40​
41 expect(isFetching()).toStrictEqual(0)
42 await vi.advanceTimersByTimeAsync(1)
43 expect(isFetching()).toStrictEqual(1)
44 await vi.advanceTimersByTimeAsync(100)
45 expect(isFetching()).toStrictEqual(0)
46 })
47​
48 describe('injection context', () => {
49 test('throws NG0203 with descriptive error outside injection context', () => {
50 expect(() => {
51 injectIsFetching()
52 }).toThrow(/NG0203(.*?)injectIsFetching/)
53 })
54​
55 test('can be used outside injection context when passing an injector', () => {
56 expect(
57 injectIsFetching(undefined, {
58 injector: TestBed.inject(Injector),
59 }),
60 ).not.toThrow()
61 })
62 })
63})