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

inject-queries.test.ts

239 lines6.7 KB

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 { createKey, 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 = createKey()
34 const key2 = createKey()
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).toHaveLength(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 = createKey()
83 const key2 = createKey()
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 = createKey()
138 const key2 = createKey()
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 = createKey()
182 const key2 = createKey()
183 const queryFn1 = vi.fn<() => Promise<number>>(() =>
184 sleep(10).then(() => 1),
185 )
186 const queryFn2 = vi.fn<() => Promise<number>>(() =>
187 sleep(10).then(() => 2),
188 )
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 await vi.advanceTimersByTimeAsync(11)
228 rendered.fixture.detectChanges()
229 expect(
230 rendered.getByText('status1: pending, fetchStatus1: idle'),
231 ).toBeInTheDocument()
232 expect(
233 rendered.getByText('status2: pending, fetchStatus2: idle'),
234 ).toBeInTheDocument()
235 expect(queryFn1).toHaveBeenCalledTimes(0)
236 expect(queryFn2).toHaveBeenCalledTimes(0)
237 })
238 })
239})