Open History to see the last commit
1import {
2 ApplicationRef,
3 ChangeDetectionStrategy,
4 Component,
5 VERSION,
6 effect,
7 input,
8 signal,
9} from '@angular/core'
10import { TestBed } from '@angular/core/testing'
11import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
12import {
13 QueryClient,
14 injectMutation,
15 injectQuery,
16 provideTanStackQuery,
17} from '..'
18import { provideAngularQueryChangeDetection } from './test-utils'
19β
20// Reproductions transcribed from TanStack/query issues. Use real promises and
21// Angular stability, without notification-scheduler overrides or timer flushes.
22describe('upstream Angular issue reproductions', () => {
23 let client: QueryClient
24β
25 beforeEach(() => {
26 vi.useRealTimers()
27 if (
28 process.env.ANGULAR_ISSUE_VERSION &&
29 VERSION.full !== process.env.ANGULAR_ISSUE_VERSION
30 ) {
31 throw new Error(`Unexpected Angular runtime: ${VERSION.full}`)
32 }
33 client = new QueryClient({
34 defaultOptions: { queries: { retry: false, gcTime: Infinity } },
35 })
36 TestBed.configureTestingModule({
37 providers: [
38 provideAngularQueryChangeDetection(),
39 provideTanStackQuery(() => client),
40 ],
41 })
42 })
43β
44 afterEach(() => {
45 TestBed.resetTestingModule()
46 client.clear()
47 })
48β
49 it('#9910: a template signal read does not prevent whenStable from seeing success', async () => {
50 @Component({ template: '{{ query.isSuccess() }}' })
51 class App {
52 query = injectQuery(() => ({
53 queryKey: ['9910'],
54 queryFn: () => Promise.resolve([1, 2, 3, 4, 5]),
55 }))
56 }
57 const fixture = TestBed.createComponent(App)
58 fixture.autoDetectChanges()
59 await fixture.whenStable()
60 fixture.detectChanges()
61 expect(fixture.componentInstance.query.isSuccess()).toBe(true)
62 expect(fixture.componentInstance.query.data()).toEqual([1, 2, 3, 4, 5])
63 expect(fixture.nativeElement.textContent).toBe('true')
64 })
65β
66 it('#10046: a class-field data alias is populated after whenStable', async () => {
67 @Component({ template: '{{ data() }}' })
68 class App {
69 query = injectQuery(() => ({
70 queryKey: ['10046'],
71 queryFn: () => Promise.resolve('loaded'),
72 }))
73 data = this.query.data
74 }
75 const fixture = TestBed.createComponent(App)
76 fixture.autoDetectChanges()
77 await fixture.whenStable()
78 fixture.detectChanges()
79 expect(fixture.componentInstance.data()).toBe('loaded')
80 expect(fixture.nativeElement.textContent).toBe('loaded')
81 })
82β
83 it.each(['TestBed', 'Testing Library'] as const)(
84 '#9981: an isSuccess effect updates component state using %s',
85 async (runner) => {
86 @Component({
87 template: '{{ value }}',
88 changeDetection: ChangeDetectionStrategy.OnPush,
89 })
90 class App {
91 value = 42
92 query = injectQuery(() => ({
93 queryKey: ['9981'],
94 queryFn: () => Promise.resolve([30, 40, 50]),
95 }))
96 constructor() {
97 effect(() => {
98 if (this.query.isSuccess()) this.value = 9999
99 })
100 }
101 }
102 const fixture =
103 runner === 'TestBed'
104 ? TestBed.createComponent(App)
105 : (await (await import('@testing-library/angular')).render(App))
106 .fixture
107 fixture.autoDetectChanges()
108 await fixture.whenStable()
109 fixture.detectChanges()
110 expect(fixture.componentInstance.value).toBe(9999)
111 },
112 )
113β
114 it('#7488: taking a data alias does not read an unset required input', async () => {
115 const optionsRead = vi.fn()
116 @Component({ template: '{{ data() }}' })
117 class App {
118 name = input.required<string>()
119 data = injectQuery(() => {
120 optionsRead()
121 return {
122 queryKey: ['7488', this.name()],
123 queryFn: () => Promise.resolve(this.name()),
124 }
125 }).data
126 }
127 const fixture = TestBed.createComponent(App)
128 expect(optionsRead).not.toHaveBeenCalled()
129 fixture.componentRef.setInput('name', 'ready')
130 fixture.autoDetectChanges()
131 await fixture.whenStable()
132 expect(fixture.componentInstance.data()).toBe('ready')
133 expect(optionsRead).toHaveBeenCalledTimes(1)
134 })
135β
136 it.each(['constructor', 'ngOnInit', 'ngAfterContentInit'] as const)(
137 '#9020: mutate immediately exposes pending from %s',
138 async (phase) => {
139 let finish!: (value: string) => void
140 const request = new Promise<string>((resolve) => {
141 finish = resolve
142 })
143 @Component({ template: '{{ mutation.status() }}' })
144 class App {
145 immediate = ''
146 mutation = injectMutation(() => ({ mutationFn: () => request }))
147 constructor() {
148 if (phase === 'constructor') this.start()
149 }
150 ngOnInit() {
151 if (phase === 'ngOnInit') this.start()
152 }
153 ngAfterContentInit() {
154 if (phase === 'ngAfterContentInit') this.start()
155 }
156 start() {
157 this.mutation.mutate()
158 this.immediate = this.mutation.status()
159 }
160 }
161 const fixture = TestBed.createComponent(App)
162 fixture.detectChanges()
163 expect(fixture.componentInstance.immediate).toBe('pending')
164 expect(fixture.nativeElement.textContent).toBe('pending')
165 finish('done')
166 await fixture.whenStable()
167 expect(fixture.componentInstance.mutation.data()).toBe('done')
168 },
169 )
170β
171 it('#11176: whenStable waits for a just-triggered fire-and-forget mutation', async () => {
172 const app = TestBed.inject(ApplicationRef)
173 const mutation = TestBed.runInInjectionContext(() =>
174 injectMutation(() => ({
175 mutationFn: (value: string) =>
176 new Promise<string>((resolve) => {
177 setTimeout(() => resolve(value), 5)
178 }),
179 })),
180 )
181 TestBed.tick()
182 mutation.mutate('mutated')
183 await app.whenStable()
184 expect(mutation.status()).toBe('success')
185 expect(mutation.data()).toBe('mutated')
186 })
187β
188 it.each([false, true])(
189 '#11176: a newer mutation settling cannot release an older invocation (reset=%s)',
190 async (reset) => {
191 let finish!: () => void
192 const first = new Promise<void>((resolve) => {
193 finish = resolve
194 })
195 const mutation = TestBed.runInInjectionContext(() =>
196 injectMutation(() => ({
197 mutationFn: (request: Promise<void>) => request,
198 })),
199 )
200 TestBed.tick()
201 mutation.mutate(first)
202 if (reset) mutation.reset()
203 const second = mutation.mutateAsync(Promise.resolve())
204 let stable = false
205 const settled = TestBed.inject(ApplicationRef)
206 .whenStable()
207 .then(() => {
208 stable = true
209 })
210 await second
211 expect(stable).toBe(false)
212 finish()
213 await settled
214 expect(stable).toBe(true)
215 },
216 )
217β
218 it('#9735: saving an edit exposes optimistic data in the same turn and render', async () => {
219 const snapshots: Array<string | undefined> = []
220 @Component({
221 template: '@if (!editing()) { <output>{{ query.data() }}</output> }',
222 changeDetection: ChangeDetectionStrategy.OnPush,
223 })
224 class App {
225 editing = signal(true)
226 query = injectQuery(() => ({
227 queryKey: ['9735'],
228 queryFn: () => Promise.resolve('old title'),
229 initialData: 'old title',
230 staleTime: Infinity,
231 }))
232 mutation = injectMutation(() => ({
233 mutationFn: async (title: string) => title,
234 onMutate: (title: string) => {
235 client.setQueryData(['9735'], title)
236 snapshots.push(this.query.data())
237 },
238 }))
239 save() {
240 this.mutation.mutate('new title')
241 this.editing.set(false)
242 snapshots.push(this.query.data())
243 }
244 }
245 const fixture = TestBed.createComponent(App)
246 fixture.detectChanges()
247 fixture.componentInstance.save()
248 expect(snapshots).toEqual(['new title', 'new title'])
249 expect(client.getQueryData(['9735'])).toBe('new title')
250 fixture.detectChanges()
251 expect(fixture.nativeElement.textContent).toBe('new title')
252 await fixture.whenStable()
253 })
254β
255 it('#6567: changing to another cached key updates data immediately', () => {
256 client.setQueryData(['6567', 'a'], 'A')
257 client.setQueryData(['6567', 'b'], 'B')
258 const key = signal('a')
259 const query = TestBed.runInInjectionContext(() =>
260 injectQuery(() => ({
261 queryKey: ['6567', key()],
262 enabled: false,
263 })),
264 )
265 expect(query.data()).toBe('A')
266 TestBed.tick()
267 key.set('b')
268 expect(query.data()).toBe('B')
269 })
270β
271 it('#6771: enabling a fresh cached query and immediately refetching settles', async () => {
272 client.setQueryData(['6771'], 'cached')
273 const enabled = signal(false)
274 const query = TestBed.runInInjectionContext(() =>
275 injectQuery(() => ({
276 queryKey: ['6771'],
277 enabled: enabled(),
278 staleTime: Infinity,
279 queryFn: () => Promise.resolve('updated'),
280 })),
281 )
282 TestBed.tick()
283 enabled.set(true)
284 await query.refetch()
285 await TestBed.inject(ApplicationRef).whenStable()
286 expect(query.data()).toBe('updated')
287 expect(query.isRefetching()).toBe(false)
288 })
289})