Open History to see the last commit
1import {
2 ChangeDetectionStrategy,
3 Component,
4 input,
5 inputBinding,
6 signal,
7} from '@angular/core'
8import { TestBed } from '@angular/core/testing'
9import { render } from '@testing-library/angular'
10import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
11import { sleep } from '@tanstack/query-test-utils'
12import {
13 QueryClient,
14 injectMutation,
15 injectMutationState,
16 provideTanStackQuery,
17} from '..'
18import { provideAngularQueryChangeDetection } from './test-utils'
19β
20describe('injectMutationState', () => {
21 let queryClient: QueryClient
22β
23 beforeEach(() => {
24 queryClient = new QueryClient()
25 vi.useFakeTimers()
26 TestBed.configureTestingModule({
27 providers: [
28 provideAngularQueryChangeDetection(),
29 provideTanStackQuery(() => queryClient),
30 ],
31 })
32 })
33β
34 afterEach(() => {
35 vi.useRealTimers()
36 })
37β
38 it('publishes selected mutation values unchanged and compares snapshot entries by identity', () => {
39 const version = signal('before')
40 queryClient.getMutationCache().build(queryClient, { mutationKey: ['a'] })
41 queryClient.getMutationCache().build(queryClient, { mutationKey: ['b'] })
42 let selected: Array<{ value: string }> = []
43 const states = TestBed.runInInjectionContext(() =>
44 injectMutationState(() => {
45 selected = []
46 return {
47 select: (m) => {
48 const value = {
49 value:
50 m.options.mutationKey![0] === 'a' ? version() : 'unchanged',
51 }
52 selected.push(value)
53 return value
54 },
55 }
56 }),
57 )
58 const before = states()
59 version.set('after')
60 const after = states()
61 expect(after[0]).toBe(selected[0])
62 expect(after[1]).toBe(selected[1])
63 expect(after[1]).not.toBe(before[1])
64 // Stable entries avoid array-only updates, without deep comparison.
65 const filter = signal('a')
66 const selectedValue = { value: 'same' }
67 const filtered = TestBed.runInInjectionContext(() =>
68 injectMutationState(() => ({
69 filters: { mutationKey: [filter()] },
70 select: () => selectedValue,
71 })),
72 )
73 const initial = filtered()
74 filter.set('b')
75 expect(filtered()).toBe(initial)
76 expect(filtered()[0]).toBe(selectedValue)
77 })
78β
79 describe('injectMutationState', () => {
80 it('should return variables after calling mutate 1', () => {
81 const mutationKey = ['mutation']
82 const variables = 'foo123'
83β
84 const mutation = TestBed.runInInjectionContext(() => {
85 return injectMutation(() => ({
86 mutationKey: mutationKey,
87 mutationFn: (params: string) => sleep(0).then(() => params),
88 }))
89 })
90β
91 mutation.mutate(variables)
92β
93 const mutationState = TestBed.runInInjectionContext(() => {
94 return injectMutationState(() => ({
95 filters: { mutationKey, status: 'pending' },
96 select: (m) => m.state.variables,
97 }))
98 })
99β
100 expect(mutationState()).toEqual([variables])
101 })
102β
103 it('reactive options should update injectMutationState', () => {
104 const mutationKey1 = ['mutation1']
105 const mutationKey2 = ['mutation2']
106 const variables1 = 'foo123'
107 const variables2 = 'bar234'
108β
109 const [mutation1, mutation2] = TestBed.runInInjectionContext(() => {
110 return [
111 injectMutation(() => ({
112 mutationKey: mutationKey1,
113 mutationFn: (params: string) => sleep(0).then(() => params),
114 })),
115 injectMutation(() => ({
116 mutationKey: mutationKey2,
117 mutationFn: (params: string) => sleep(0).then(() => params),
118 })),
119 ]
120 })
121β
122 mutation1.mutate(variables1)
123 mutation2.mutate(variables2)
124β
125 const filterKey = signal(mutationKey1)
126β
127 const mutationState = TestBed.runInInjectionContext(() => {
128 return injectMutationState(() => ({
129 filters: { mutationKey: filterKey(), status: 'pending' },
130 select: (m) => m.state.variables,
131 }))
132 })
133β
134 expect(mutationState()).toEqual([variables1])
135β
136 filterKey.set(mutationKey2)
137 expect(mutationState()).toEqual([variables2])
138 })
139β
140 it('preserves result identity when an unrelated mutation changes', () => {
141 const mutationState = TestBed.runInInjectionContext(() =>
142 injectMutationState(() => ({
143 filters: { mutationKey: ['matching'] },
144 })),
145 )
146 const unrelatedMutation = TestBed.runInInjectionContext(() =>
147 injectMutation(() => ({
148 mutationKey: ['unrelated'],
149 mutationFn: () => Promise.resolve(),
150 })),
151 )
152 const initialResult = mutationState()
153β
154 unrelatedMutation.mutate()
155β
156 expect(mutationState()).toBe(initialResult)
157 })
158β
159 it('should return variables after calling mutate 2', () => {
160 queryClient.clear()
161 const mutationKey = ['mutation']
162 const variables = 'bar234'
163β
164 const mutation = TestBed.runInInjectionContext(() => {
165 return injectMutation(() => ({
166 mutationKey: mutationKey,
167 mutationFn: (params: string) => sleep(0).then(() => params),
168 }))
169 })
170β
171 mutation.mutate(variables)
172β
173 const mutationState = TestBed.runInInjectionContext(() => {
174 return injectMutationState()
175 })
176β
177 expect(mutationState()[0]?.variables).toEqual(variables)
178 })
179β
180 it('should support required signal inputs', async () => {
181 queryClient.clear()
182 const fakeName = 'name1'
183 const mutationKey1 = ['fake', fakeName]
184β
185 const mutations = TestBed.runInInjectionContext(() => {
186 return [
187 injectMutation(() => ({
188 mutationKey: mutationKey1,
189 mutationFn: () => sleep(10).then(() => 'myValue'),
190 })),
191 injectMutation(() => ({
192 mutationKey: mutationKey1,
193 mutationFn: () =>
194 sleep(10).then(() => Promise.reject(new Error('myValue2'))),
195 })),
196 ]
197 })
198β
199 mutations.forEach((mutation) => mutation.mutate())
200β
201 @Component({
202 selector: 'app-fake',
203 template: `
204 @for (mutation of mutationState(); track $index) {
205 <span>{{ mutation.status }}</span>
206 }
207 `,
208 changeDetection: ChangeDetectionStrategy.OnPush,
209 })
210 class FakeComponent {
211 name = input.required<string>()
212β
213 mutationState = injectMutationState(() => ({
214 filters: {
215 mutationKey: ['fake', this.name()],
216 exact: true,
217 },
218 }))
219 }
220β
221 TestBed.resetTestingModule()
222 const name = signal(fakeName)
223 const rendered = await render(FakeComponent, {
224 providers: [
225 provideAngularQueryChangeDetection(),
226 provideTanStackQuery(() => queryClient),
227 ],
228 bindings: [inputBinding('name', name.asReadonly())],
229 detectChangesOnRender: false,
230 })
231 rendered.fixture.detectChanges()
232β
233 await vi.advanceTimersByTimeAsync(0)
234β
235 expect(rendered.getAllByText('pending')).toHaveLength(2)
236β
237 await vi.advanceTimersByTimeAsync(11)
238 rendered.fixture.detectChanges()
239β
240 expect(rendered.getByText('success')).toBeInTheDocument()
241 expect(rendered.getByText('error')).toBeInTheDocument()
242 })
243β
244 describe('injection context', () => {
245 it('throws NG0203 with descriptive error outside injection context', () => {
246 expect(() => {
247 injectMutationState()
248 }).toThrowError(/NG0203(.*?)injectMutationState/)
249 })
250 })
251 })
252})