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

inject-is-fetching.test.ts

78 lines2.0 KB

1import { TestBed } from '@angular/core/testing'
2import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
3import {
4 Component,
5 Injector,
6 provideZonelessChangeDetection,
7} from '@angular/core'
8import { render } from '@testing-library/angular'
9import { queryKey, sleep } from '@tanstack/query-test-utils'
10import {
11 QueryClient,
12 injectIsFetching,
13 injectQuery,
14 provideTanStackQuery,
15} from '..'
16​
17describe('injectIsFetching', () => {
18 let queryClient: QueryClient
19​
20 beforeEach(() => {
21 vi.useFakeTimers()
22 queryClient = new QueryClient()
23​
24 TestBed.configureTestingModule({
25 providers: [
26 provideZonelessChangeDetection(),
27 provideTanStackQuery(queryClient),
28 ],
29 })
30 })
31​
32 afterEach(() => {
33 vi.useRealTimers()
34 })
35​
36 it('should return the number of fetching queries', async () => {
37 const key = queryKey()
38​
39 @Component({
40 template: `<div>fetching: {{ isFetching() }}</div>`,
41 })
42 class Page {
43 readonly query = injectQuery(() => ({
44 queryKey: key,
45 queryFn: () => sleep(100).then(() => 'Some data'),
46 }))
47 readonly isFetching = injectIsFetching()
48 }
49​
50 const rendered = await render(Page)
51​
52 expect(rendered.getByText('fetching: 0')).toBeInTheDocument()
53​
54 await vi.advanceTimersByTimeAsync(0)
55 rendered.fixture.detectChanges()
56 expect(rendered.getByText('fetching: 1')).toBeInTheDocument()
57​
58 await vi.advanceTimersByTimeAsync(101)
59 rendered.fixture.detectChanges()
60 expect(rendered.getByText('fetching: 0')).toBeInTheDocument()
61 })
62​
63 describe('injection context', () => {
64 it('should throw NG0203 with descriptive error outside injection context', () => {
65 expect(() => {
66 injectIsFetching()
67 }).toThrow(/NG0203(.*?)injectIsFetching/)
68 })
69​
70 it('should be usable outside injection context when passing an injector', () => {
71 expect(
72 injectIsFetching(undefined, {
73 injector: TestBed.inject(Injector),
74 }),
75 ).not.toThrow()
76 })
77 })
78})