Open History to see the last commit
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 await vi.advanceTimersByTimeAsync(0)
54 rendered.fixture.detectChanges()
55 expect(rendered.getByText('fetching: 1')).toBeInTheDocument()
56 await vi.advanceTimersByTimeAsync(101)
57 rendered.fixture.detectChanges()
58 expect(rendered.getByText('fetching: 0')).toBeInTheDocument()
59 })
60β
61 it('should be able to filter by queryKey', async () => {
62 const key1 = queryKey()
63 const key2 = queryKey()
64β
65 @Component({
66 template: `<div>fetching: {{ isFetching() }}</div>`,
67 })
68 class Page {
69 readonly query1 = injectQuery(() => ({
70 queryKey: key1,
71 queryFn: () => sleep(10).then(() => 'test1'),
72 }))
73 readonly query2 = injectQuery(() => ({
74 queryKey: key2,
75 queryFn: () => sleep(100).then(() => 'test2'),
76 }))
77 readonly isFetching = injectIsFetching({ queryKey: key1 })
78 }
79β
80 const rendered = await render(Page)
81β
82 await vi.advanceTimersByTimeAsync(0)
83 rendered.fixture.detectChanges()
84 expect(rendered.getByText('fetching: 1')).toBeInTheDocument()
85 await vi.advanceTimersByTimeAsync(11)
86 rendered.fixture.detectChanges()
87 expect(rendered.getByText('fetching: 0')).toBeInTheDocument()
88 })
89β
90 describe('injection context', () => {
91 it('should throw NG0203 with descriptive error outside injection context', () => {
92 expect(() => {
93 injectIsFetching()
94 }).toThrow(/NG0203(.*?)injectIsFetching/)
95 })
96β
97 it('should be usable outside injection context when passing an injector', () => {
98 expect(
99 injectIsFetching(undefined, {
100 injector: TestBed.inject(Injector),
101 }),
102 ).not.toThrow()
103 })
104 })
105})