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 expect(rendered.getByText('data1: 1, data2: 2')).toBeInTheDocument()
74β
75 expect(results.length).toBe(3)
76 expect(results[0]).toMatchObject([{ data: undefined }, { data: undefined }])
77 expect(results[1]).toMatchObject([{ data: 1 }, { data: undefined }])
78 expect(results[2]).toMatchObject([{ data: 1 }, { data: 2 }])
79 })
80β
81 it('should return the combined result when combine is provided', async () => {
82 const key1 = queryKey()
83 const key2 = queryKey()
84 const results: Array<Record<string, any>> = []
85β
86 @Component({
87 template: `
88 <div>data: {{ combined().data.join(',') }}</div>
89 <div>isPending: {{ combined().isPending }}</div>
90 `,
91 })
92 class Page {
93 readonly combined = injectQueries(() => ({
94 queries: [
95 {
96 queryKey: key1,
97 queryFn: () => sleep(10).then(() => 1),
98 },
99 {
100 queryKey: key2,
101 queryFn: () => sleep(10).then(() => 2),
102 },
103 ],
104 combine: (queries) => ({
105 data: queries.map((q) => q.data),
106 isPending: queries.some((q) => q.isPending),
107 }),
108 }))
109β
110 constructor() {
111 effect(() => {
112 results.push({ ...this.combined() })
113 })
114 }
115 }
116β
117 const rendered = await render(Page)
118β
119 expect(rendered.getByText('data: ,')).toBeInTheDocument()
120 expect(rendered.getByText('isPending: true')).toBeInTheDocument()
121 expect(results[0]).toMatchObject({
122 data: [undefined, undefined],
123 isPending: true,
124 })
125 await vi.advanceTimersByTimeAsync(11)
126 rendered.fixture.detectChanges()
127 expect(rendered.getByText('data: 1,2')).toBeInTheDocument()
128 expect(rendered.getByText('isPending: false')).toBeInTheDocument()
129 expect(results[results.length - 1]).toMatchObject({
130 data: [1, 2],
131 isPending: false,
132 })
133 expect(results.length).toBeGreaterThanOrEqual(2)
134 })
135β
136 it('should reflect error state when one of the queries rejects', async () => {
137 const key1 = queryKey()
138 const key2 = queryKey()
139β
140 @Component({
141 template: `
142 <div>
143 status1: {{ result()[0].status() }}, error1:
144 {{ result()[0].error()?.message ?? 'none' }}
145 </div>
146 <div>
147 status2: {{ result()[1].status() }}, data2:
148 {{ result()[1].data() ?? 'none' }}
149 </div>
150 `,
151 })
152 class Page {
153 readonly result = injectQueries(() => ({
154 queries: [
155 {
156 queryKey: key1,
157 queryFn: () =>
158 sleep(10).then(() => Promise.reject(new Error('Some error'))),
159 retry: false,
160 },
161 {
162 queryKey: key2,
163 queryFn: () => sleep(10).then(() => 2),
164 },
165 ],
166 }))
167 }
168β
169 const rendered = await render(Page)
170β
171 await vi.advanceTimersByTimeAsync(11)
172 rendered.fixture.detectChanges()
173 expect(
174 rendered.getByText('status1: error, error1: Some error'),
175 ).toBeInTheDocument()
176 expect(rendered.getByText('status2: success, data2: 2')).toBeInTheDocument()
177 })
178β
179 describe('isRestoring', () => {
180 it('should not fetch for the duration of the restoring period when isRestoring is true', async () => {
181 const key1 = queryKey()
182 const key2 = queryKey()
183 const queryFn1 = vi.fn().mockImplementation(() => sleep(10).then(() => 1))
184 const queryFn2 = vi.fn().mockImplementation(() => sleep(10).then(() => 2))
185β
186 TestBed.configureTestingModule({
187 providers: [provideIsRestoring(signal(true).asReadonly())],
188 })
189β
190 @Component({
191 template: `
192 <div>
193 status1: {{ queries()[0].status() }}, fetchStatus1:
194 {{ queries()[0].fetchStatus() }}
195 </div>
196 <div>
197 status2: {{ queries()[1].status() }}, fetchStatus2:
198 {{ queries()[1].fetchStatus() }}
199 </div>
200 `,
201 })
202 class Page {
203 readonly queries = injectQueries(() => ({
204 queries: [
205 { queryKey: key1, queryFn: queryFn1 },
206 { queryKey: key2, queryFn: queryFn2 },
207 ],
208 }))
209 }
210β
211 const rendered = await render(Page)
212β
213 await vi.advanceTimersByTimeAsync(0)
214 rendered.fixture.detectChanges()
215 expect(
216 rendered.getByText('status1: pending, fetchStatus1: idle'),
217 ).toBeInTheDocument()
218 expect(
219 rendered.getByText('status2: pending, fetchStatus2: idle'),
220 ).toBeInTheDocument()
221 expect(queryFn1).toHaveBeenCalledTimes(0)
222 expect(queryFn2).toHaveBeenCalledTimes(0)
223 await vi.advanceTimersByTimeAsync(11)
224 rendered.fixture.detectChanges()
225 expect(
226 rendered.getByText('status1: pending, fetchStatus1: idle'),
227 ).toBeInTheDocument()
228 expect(
229 rendered.getByText('status2: pending, fetchStatus2: idle'),
230 ).toBeInTheDocument()
231 expect(queryFn1).toHaveBeenCalledTimes(0)
232 expect(queryFn2).toHaveBeenCalledTimes(0)
233 })
234 })
235})