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

upstream-issues.test.ts

292 lines9.1 KB

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()).toStrictEqual([
63 1, 2, 3, 4, 5,
64 ])
65 expect(fixture.nativeElement.textContent).toBe('true')
66 })
67​
68 it('#10046: a class-field data alias is populated after whenStable', async () => {
69 @Component({ template: '{{ data() }}' })
70 class App {
71 query = injectQuery(() => ({
72 queryKey: ['10046'],
73 queryFn: () => Promise.resolve('loaded'),
74 }))
75 data = this.query.data
76 }
77 const fixture = TestBed.createComponent(App)
78 fixture.autoDetectChanges()
79 await fixture.whenStable()
80 fixture.detectChanges()
81 expect(fixture.componentInstance.data()).toBe('loaded')
82 expect(fixture.nativeElement.textContent).toBe('loaded')
83 })
84​
85 it.each(['TestBed', 'Testing Library'] as const)(
86 '#9981: an isSuccess effect updates component state using %s',
87 async (runner) => {
88 @Component({
89 template: '{{ value }}',
90 changeDetection: ChangeDetectionStrategy.OnPush,
91 })
92 class App {
93 value = 42
94 query = injectQuery(() => ({
95 queryKey: ['9981'],
96 queryFn: () => Promise.resolve([30, 40, 50]),
97 }))
98 constructor() {
99 effect(() => {
100 if (this.query.isSuccess()) this.value = 9999
101 })
102 }
103 }
104 const fixture =
105 runner === 'TestBed'
106 ? TestBed.createComponent(App)
107 : (await (await import('@testing-library/angular')).render(App))
108 .fixture
109 fixture.autoDetectChanges()
110 await fixture.whenStable()
111 fixture.detectChanges()
112 expect(fixture.componentInstance.value).toBe(9999)
113 },
114 )
115​
116 it('#7488: taking a data alias does not read an unset required input', async () => {
117 const optionsRead = vi.fn<() => void>()
118 @Component({ template: '{{ data() }}' })
119 class App {
120 name = input.required<string>()
121 data = injectQuery(() => {
122 optionsRead()
123 return {
124 queryKey: ['7488', this.name()],
125 queryFn: () => Promise.resolve(this.name()),
126 }
127 }).data
128 }
129 const fixture = TestBed.createComponent(App)
130 expect(optionsRead).not.toHaveBeenCalled()
131 fixture.componentRef.setInput('name', 'ready')
132 fixture.autoDetectChanges()
133 await fixture.whenStable()
134 expect(fixture.componentInstance.data()).toBe('ready')
135 expect(optionsRead).toHaveBeenCalledTimes(1)
136 })
137​
138 it.each(['constructor', 'ngOnInit', 'ngAfterContentInit'] as const)(
139 '#9020: mutate immediately exposes pending from %s',
140 async (phase) => {
141 let finish!: (value: string) => void
142 const request = new Promise<string>((resolve) => {
143 finish = resolve
144 })
145 @Component({ template: '{{ mutation.status() }}' })
146 class App {
147 immediate = ''
148 mutation = injectMutation(() => ({ mutationFn: () => request }))
149 constructor() {
150 if (phase === 'constructor') this.start()
151 }
152 ngOnInit() {
153 if (phase === 'ngOnInit') this.start()
154 }
155 ngAfterContentInit() {
156 if (phase === 'ngAfterContentInit') this.start()
157 }
158 start() {
159 this.mutation.mutate()
160 this.immediate = this.mutation.status()
161 }
162 }
163 const fixture = TestBed.createComponent(App)
164 fixture.detectChanges()
165 expect(fixture.componentInstance.immediate).toBe('pending')
166 expect(fixture.nativeElement.textContent).toBe('pending')
167 finish('done')
168 await fixture.whenStable()
169 expect(fixture.componentInstance.mutation.data()).toBe('done')
170 },
171 )
172​
173 it('#11176: whenStable waits for a just-triggered fire-and-forget mutation', async () => {
174 const app = TestBed.inject(ApplicationRef)
175 const mutation = TestBed.runInInjectionContext(() =>
176 injectMutation(() => ({
177 mutationFn: (value: string) =>
178 new Promise<string>((resolve) => {
179 setTimeout(() => resolve(value), 5)
180 }),
181 })),
182 )
183 TestBed.tick()
184 mutation.mutate('mutated')
185 await app.whenStable()
186 expect(mutation.status()).toBe('success')
187 expect(mutation.data()).toBe('mutated')
188 })
189​
190 it.each([false, true])(
191 '#11176: a newer mutation settling cannot release an older invocation (reset=%s)',
192 async (reset) => {
193 let finish!: () => void
194 const first = new Promise<void>((resolve) => {
195 finish = resolve
196 })
197 const mutation = TestBed.runInInjectionContext(() =>
198 injectMutation(() => ({
199 mutationFn: (request: Promise<void>) => request,
200 })),
201 )
202 TestBed.tick()
203 mutation.mutate(first)
204 // oxlint-disable-next-line vitest-js/no-conditional-in-test -- The parameter selects setup/actions; every case runs the assertions.
205 if (reset) mutation.reset()
206 const second = mutation.mutateAsync(Promise.resolve())
207 let stable = false
208 const settled = TestBed.inject(ApplicationRef)
209 .whenStable()
210 .then(() => {
211 stable = true
212 })
213 await second
214 expect(stable).toBe(false)
215 finish()
216 await settled
217 expect(stable).toBe(true)
218 },
219 )
220​
221 it('#9735: saving an edit exposes optimistic data in the same turn and render', async () => {
222 const snapshots: Array<string | undefined> = []
223 @Component({
224 template: '@if (!editing()) { <output>{{ query.data() }}</output> }',
225 changeDetection: ChangeDetectionStrategy.OnPush,
226 })
227 class App {
228 editing = signal(true)
229 query = injectQuery(() => ({
230 queryKey: ['9735'],
231 queryFn: () => Promise.resolve('old title'),
232 initialData: 'old title',
233 staleTime: Infinity,
234 }))
235 mutation = injectMutation(() => ({
236 mutationFn: async (title: string) => title,
237 onMutate: (title: string) => {
238 client.setQueryData(['9735'], title)
239 snapshots.push(this.query.data())
240 },
241 }))
242 save() {
243 this.mutation.mutate('new title')
244 this.editing.set(false)
245 snapshots.push(this.query.data())
246 }
247 }
248 const fixture = TestBed.createComponent(App)
249 fixture.detectChanges()
250 fixture.componentInstance.save()
251 expect(snapshots).toStrictEqual(['new title', 'new title'])
252 expect(client.getQueryData(['9735'])).toBe('new title')
253 fixture.detectChanges()
254 expect(fixture.nativeElement.textContent).toBe('new title')
255 await fixture.whenStable()
256 })
257​
258 it('#6567: changing to another cached key updates data immediately', () => {
259 client.setQueryData(['6567', 'a'], 'A')
260 client.setQueryData(['6567', 'b'], 'B')
261 const key = signal('a')
262 const query = TestBed.runInInjectionContext(() =>
263 injectQuery(() => ({
264 queryKey: ['6567', key()],
265 enabled: false,
266 })),
267 )
268 expect(query.data()).toBe('A')
269 TestBed.tick()
270 key.set('b')
271 expect(query.data()).toBe('B')
272 })
273​
274 it('#6771: enabling a fresh cached query and immediately refetching settles', async () => {
275 client.setQueryData(['6771'], 'cached')
276 const enabled = signal(false)
277 const query = TestBed.runInInjectionContext(() =>
278 injectQuery(() => ({
279 queryKey: ['6771'],
280 enabled: enabled(),
281 staleTime: Infinity,
282 queryFn: () => Promise.resolve('updated'),
283 })),
284 )
285 TestBed.tick()
286 enabled.set(true)
287 await query.refetch()
288 await TestBed.inject(ApplicationRef).whenStable()
289 expect(query.data()).toBe('updated')
290 expect(query.isRefetching()).toBe(false)
291 })
292})