Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import {
3 Component,
4 effect,
5 provideZonelessChangeDetection,
6 signal,
7} from '@angular/core'
8import { TestBed } from '@angular/core/testing'
9import { render } from '@testing-library/angular'
10import { queryKey, sleep } from '@tanstack/query-test-utils'
11import { QueryClient, provideIsRestoring, provideTanStackQuery } from '..'
12import { injectQueries } from '../inject-queries'
13β
14describe('injectQueries', () => {
15 let queryClient: QueryClient
16β
17 beforeEach(() => {
18 vi.useFakeTimers()
19 queryClient = new QueryClient()
20 TestBed.configureTestingModule({
21 providers: [
22 provideZonelessChangeDetection(),
23 provideTanStackQuery(queryClient),
24 ],
25 })
26 })
27β
28 afterEach(() => {
29 vi.useRealTimers()
30 })
31β
32 it('should return the correct states', async () => {
33 const key1 = queryKey()
34 const key2 = queryKey()
35 const results: Array<Array<Record<string, any>>> = []
36β
37 @Component({
38 template: `
39 <div>
40 <div>
41 data1: {{ result()[0].data() ?? 'null' }}, data2:
42 {{ result()[1].data() ?? 'null' }}
43 </div>
44 </div>
45 `,
46 })
47 class Page {
48 readonly result = injectQueries(() => ({
49 queries: [
50 {
51 queryKey: key1,
52 queryFn: () => sleep(10).then(() => 1),
53 },
54 {
55 queryKey: key2,
56 queryFn: () => sleep(100).then(() => 2),
57 },
58 ],
59 }))
60β
61 constructor() {
62 effect(() => {
63 const snapshot = this.result().map((q) => ({ data: q.data() }))
64 results.push(snapshot)
65 })
66 }
67 }
68β
69 const rendered = await render(Page)
70β
71 await vi.advanceTimersByTimeAsync(101)
72 rendered.fixture.detectChanges()
73β
74 expect(rendered.getByText('data1: 1, data2: 2')).toBeInTheDocument()
75β
76 expect(results.length).toBe(3)
77 expect(results[0]).toMatchObject([{ data: undefined }, { data: undefined }])
78 expect(results[1]).toMatchObject([{ data: 1 }, { data: undefined }])
79 expect(results[2]).toMatchObject([{ data: 1 }, { data: 2 }])
80 })
81β
82 it('should return the combined result when combine is provided', async () => {
83 const key1 = queryKey()
84 const key2 = queryKey()
85 const results: Array<Record<string, any>> = []
86β
87 @Component({
88 template: `
89 <div>data: {{ combined().data.join(',') }}</div>
90 <div>isPending: {{ combined().isPending }}</div>
91 `,
92 })
93 class Page {
94 readonly combined = injectQueries(() => ({
95 queries: [
96 {
97 queryKey: key1,
98 queryFn: () => sleep(10).then(() => 1),
99 },
100 {
101 queryKey: key2,
102 queryFn: () => sleep(10).then(() => 2),
103 },
104 ],
105 combine: (queries) => ({
106 data: queries.map((q) => q.data),
107 isPending: queries.some((q) => q.isPending),
108 }),
109 }))
110β
111 constructor() {
112 effect(() => {
113 results.push({ ...this.combined() })
114 })
115 }
116 }
117β
118 const rendered = await render(Page)
119β
120 expect(rendered.getByText('data: ,')).toBeInTheDocument()
121 expect(rendered.getByText('isPending: true')).toBeInTheDocument()
122 expect(results[0]).toMatchObject({
123 data: [undefined, undefined],
124 isPending: true,
125 })
126β
127 await vi.advanceTimersByTimeAsync(11)
128 rendered.fixture.detectChanges()
129β
130 expect(rendered.getByText('data: 1,2')).toBeInTheDocument()
131 expect(rendered.getByText('isPending: false')).toBeInTheDocument()
132 expect(results[results.length - 1]).toMatchObject({
133 data: [1, 2],
134 isPending: false,
135 })
136 expect(results.length).toBeGreaterThanOrEqual(2)
137 })
138β
139 it('should reflect error state when one of the queries rejects', async () => {
140 const key1 = queryKey()
141 const key2 = queryKey()
142β
143 @Component({
144 template: `
145 <div>
146 status1: {{ result()[0].status() }}, error1:
147 {{ result()[0].error()?.message ?? 'none' }}
148 </div>
149 <div>
150 status2: {{ result()[1].status() }}, data2:
151 {{ result()[1].data() ?? 'none' }}
152 </div>
153 `,
154 })
155 class Page {
156 readonly result = injectQueries(() => ({
157 queries: [
158 {
159 queryKey: key1,
160 queryFn: () =>
161 sleep(10).then(() => Promise.reject(new Error('Some error'))),
162 retry: false,
163 },
164 {
165 queryKey: key2,
166 queryFn: () => sleep(10).then(() => 2),
167 },
168 ],
169 }))
170 }
171β
172 const rendered = await render(Page)
173β
174 await vi.advanceTimersByTimeAsync(11)
175 rendered.fixture.detectChanges()
176β
177 expect(
178 rendered.getByText('status1: error, error1: Some error'),
179 ).toBeInTheDocument()
180 expect(rendered.getByText('status2: success, data2: 2')).toBeInTheDocument()
181 })
182β
183 describe('isRestoring', () => {
184 it('should not fetch for the duration of the restoring period when isRestoring is true', async () => {
185 const key1 = queryKey()
186 const key2 = queryKey()
187 const queryFn1 = vi.fn().mockImplementation(() => sleep(10).then(() => 1))
188 const queryFn2 = vi.fn().mockImplementation(() => sleep(10).then(() => 2))
189β
190 TestBed.configureTestingModule({
191 providers: [provideIsRestoring(signal(true).asReadonly())],
192 })
193β
194 @Component({
195 template: `
196 <div>
197 status1: {{ queries()[0].status() }}, fetchStatus1:
198 {{ queries()[0].fetchStatus() }}
199 </div>
200 <div>
201 status2: {{ queries()[1].status() }}, fetchStatus2:
202 {{ queries()[1].fetchStatus() }}
203 </div>
204 `,
205 })
206 class Page {
207 readonly queries = injectQueries(() => ({
208 queries: [
209 { queryKey: key1, queryFn: queryFn1 },
210 { queryKey: key2, queryFn: queryFn2 },
211 ],
212 }))
213 }
214β
215 const rendered = await render(Page)
216β
217 await vi.advanceTimersByTimeAsync(0)
218 rendered.fixture.detectChanges()
219 expect(
220 rendered.getByText('status1: pending, fetchStatus1: idle'),
221 ).toBeInTheDocument()
222 expect(
223 rendered.getByText('status2: pending, fetchStatus2: idle'),
224 ).toBeInTheDocument()
225 expect(queryFn1).toHaveBeenCalledTimes(0)
226 expect(queryFn2).toHaveBeenCalledTimes(0)
227β
228 await vi.advanceTimersByTimeAsync(11)
229 rendered.fixture.detectChanges()
230 expect(
231 rendered.getByText('status1: pending, fetchStatus1: idle'),
232 ).toBeInTheDocument()
233 expect(
234 rendered.getByText('status2: pending, fetchStatus2: idle'),
235 ).toBeInTheDocument()
236 expect(queryFn1).toHaveBeenCalledTimes(0)
237 expect(queryFn2).toHaveBeenCalledTimes(0)
238 })
239 })
240})