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

inject-is-fetching.test.ts

62 lines1.6 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​
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 isFetching = TestBed.runInInjectionContext(() => {
33 injectQuery(() => ({
34 queryKey: ['isFetching1'],
35 queryFn: () => sleep(100).then(() => 'Some data'),
36 }))
37 return injectIsFetching()
38 })
39​
40 expect(isFetching()).toStrictEqual(0)
41 await vi.advanceTimersByTimeAsync(1)
42 expect(isFetching()).toStrictEqual(1)
43 await vi.advanceTimersByTimeAsync(100)
44 expect(isFetching()).toStrictEqual(0)
45 })
46​
47 describe('injection context', () => {
48 test('throws NG0203 with descriptive error outside injection context', () => {
49 expect(() => {
50 injectIsFetching()
51 }).toThrowError(/NG0203(.*?)injectIsFetching/)
52 })
53​
54 test('can be used outside injection context when passing an injector', () => {
55 expect(
56 injectIsFetching(undefined, {
57 injector: TestBed.inject(Injector),
58 }),
59 ).not.toThrow()
60 })
61 })
62})