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

inject-is-fetching.test.ts

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