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

inject-mutation-state.test.ts

213 lines5.8 KB

1import {
2 ChangeDetectionStrategy,
3 Component,
4 Injector,
5 input,
6 inputBinding,
7 provideZonelessChangeDetection,
8 signal,
9} from '@angular/core'
10import { TestBed } from '@angular/core/testing'
11import { render } from '@testing-library/angular'
12import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
13import { sleep } from '@tanstack/query-test-utils'
14import {
15 QueryClient,
16 injectMutation,
17 injectMutationState,
18 provideTanStackQuery,
19} from '..'
20​
21describe('injectMutationState', () => {
22 let queryClient: QueryClient
23​
24 beforeEach(() => {
25 queryClient = new QueryClient()
26 vi.useFakeTimers()
27 TestBed.configureTestingModule({
28 providers: [
29 provideZonelessChangeDetection(),
30 ...provideTanStackQuery(queryClient),
31 ],
32 })
33 })
34​
35 afterEach(() => {
36 vi.useRealTimers()
37 })
38​
39 describe('injectMutationState', () => {
40 it('should return variables after calling mutate 1', () => {
41 const mutationKey = ['mutation']
42 const variables = 'foo123'
43​
44 const mutation = TestBed.runInInjectionContext(() => {
45 return injectMutation(() => ({
46 mutationKey: mutationKey,
47 mutationFn: (params: string) => sleep(0).then(() => params),
48 }))
49 })
50​
51 mutation.mutate(variables)
52​
53 const mutationState = TestBed.runInInjectionContext(() => {
54 return injectMutationState(() => ({
55 filters: { mutationKey, status: 'pending' },
56 select: (m) => m.state.variables,
57 }))
58 })
59​
60 expect(mutationState()).toEqual([variables])
61 })
62​
63 it('reactive options should update injectMutationState', () => {
64 const mutationKey1 = ['mutation1']
65 const mutationKey2 = ['mutation2']
66 const variables1 = 'foo123'
67 const variables2 = 'bar234'
68​
69 const [mutation1, mutation2] = TestBed.runInInjectionContext(() => {
70 return [
71 injectMutation(() => ({
72 mutationKey: mutationKey1,
73 mutationFn: (params: string) => sleep(0).then(() => params),
74 })),
75 injectMutation(() => ({
76 mutationKey: mutationKey2,
77 mutationFn: (params: string) => sleep(0).then(() => params),
78 })),
79 ]
80 })
81​
82 mutation1.mutate(variables1)
83 mutation2.mutate(variables2)
84​
85 const filterKey = signal(mutationKey1)
86​
87 const mutationState = TestBed.runInInjectionContext(() => {
88 return injectMutationState(() => ({
89 filters: { mutationKey: filterKey(), status: 'pending' },
90 select: (m) => m.state.variables,
91 }))
92 })
93​
94 expect(mutationState()).toEqual([variables1])
95​
96 filterKey.set(mutationKey2)
97 expect(mutationState()).toEqual([variables2])
98 })
99​
100 it('should return variables after calling mutate 2', () => {
101 queryClient.clear()
102 const mutationKey = ['mutation']
103 const variables = 'bar234'
104​
105 const mutation = TestBed.runInInjectionContext(() => {
106 return injectMutation(() => ({
107 mutationKey: mutationKey,
108 mutationFn: (params: string) => sleep(0).then(() => params),
109 }))
110 })
111​
112 mutation.mutate(variables)
113​
114 const mutationState = TestBed.runInInjectionContext(() => {
115 return injectMutationState()
116 })
117​
118 expect(mutationState()[0]?.variables).toEqual(variables)
119 })
120​
121 it('should support required signal inputs', async () => {
122 queryClient.clear()
123 const fakeName = 'name1'
124 const mutationKey1 = ['fake', fakeName]
125​
126 const mutations = TestBed.runInInjectionContext(() => {
127 return [
128 injectMutation(() => ({
129 mutationKey: mutationKey1,
130 mutationFn: () => sleep(10).then(() => 'myValue'),
131 })),
132 injectMutation(() => ({
133 mutationKey: mutationKey1,
134 mutationFn: () =>
135 sleep(10).then(() => Promise.reject(new Error('myValue2'))),
136 })),
137 ]
138 })
139​
140 mutations.forEach((mutation) => mutation.mutate())
141​
142 @Component({
143 selector: 'app-fake',
144 template: `
145 @for (mutation of mutationState(); track $index) {
146 <span>{{ mutation.status }}</span>
147 }
148 `,
149 changeDetection: ChangeDetectionStrategy.OnPush,
150 })
151 class FakeComponent {
152 name = input.required<string>()
153​
154 mutationState = injectMutationState(() => ({
155 filters: {
156 mutationKey: ['fake', this.name()],
157 exact: true,
158 },
159 }))
160 }
161​
162 TestBed.resetTestingModule()
163 const name = signal(fakeName)
164 const rendered = await render(FakeComponent, {
165 providers: [
166 provideZonelessChangeDetection(),
167 ...provideTanStackQuery(queryClient),
168 ],
169 bindings: [inputBinding('name', name.asReadonly())],
170 detectChangesOnRender: false,
171 })
172 rendered.fixture.detectChanges()
173​
174 const fixture = rendered.fixture
175 await vi.advanceTimersByTimeAsync(0)
176​
177 const readSpans = () =>
178 Array.from(
179 fixture.nativeElement.querySelectorAll(
180 'span',
181 ) as NodeListOf<HTMLSpanElement>,
182 ).map((span) => span.textContent)
183​
184 let spans = readSpans()
185​
186 expect(spans).toEqual(['pending', 'pending'])
187​
188 await vi.advanceTimersByTimeAsync(11)
189 fixture.detectChanges()
190​
191 spans = readSpans()
192​
193 expect(spans).toEqual(['success', 'error'])
194 })
195​
196 describe('injection context', () => {
197 it('throws NG0203 with descriptive error outside injection context', () => {
198 expect(() => {
199 injectMutationState()
200 }).toThrowError(/NG0203(.*?)injectMutationState/)
201 })
202​
203 it('can be used outside injection context when passing an injector', () => {
204 const injector = TestBed.inject(Injector)
205 expect(
206 injectMutationState(undefined, {
207 injector,
208 }),
209 ).not.toThrow()
210 })
211 })
212 })
213})