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

useIsMutating.test.tsx

303 lines8.1 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import { fireEvent, render } from '@solidjs/testing-library'
3import { Show, createEffect, createRenderEffect, createSignal } from 'solid-js'
4import * as QueryCore from '@tanstack/query-core'
5import { queryKey, sleep } from '@tanstack/query-test-utils'
6import { QueryClient, useIsMutating, useMutation } from '..'
7import { renderWithClient, setActTimeout } from './utils'
8​
9describe('useIsMutating', () => {
10 let queryClient: QueryClient
11​
12 beforeEach(() => {
13 vi.useFakeTimers()
14 queryClient = new QueryClient()
15 })
16​
17 afterEach(() => {
18 queryClient.clear()
19 vi.useRealTimers()
20 })
21​
22 it('should return the number of fetching mutations', async () => {
23 const isMutatingArray: Array<number> = []
24 const mutationKey1 = queryKey()
25 const mutationKey2 = queryKey()
26​
27 function IsMutating() {
28 const isMutating = useIsMutating()
29​
30 createRenderEffect(() => {
31 isMutatingArray.push(isMutating())
32 })
33​
34 return null
35 }
36​
37 function Mutations() {
38 const { mutate: mutate1 } = useMutation(() => ({
39 mutationKey: mutationKey1,
40 mutationFn: () => sleep(150).then(() => 'data'),
41 }))
42 const { mutate: mutate2 } = useMutation(() => ({
43 mutationKey: mutationKey2,
44 mutationFn: () => sleep(50).then(() => 'data'),
45 }))
46​
47 createEffect(() => {
48 mutate1()
49 setActTimeout(() => {
50 mutate2()
51 }, 50)
52 })
53​
54 return null
55 }
56​
57 function Page() {
58 return (
59 <div>
60 <IsMutating />
61 <Mutations />
62 </div>
63 )
64 }
65​
66 renderWithClient(queryClient, () => <Page />)
67​
68 await vi.advanceTimersByTimeAsync(150)
69​
70 expect(isMutatingArray).toEqual([0, 1, 2, 1, 0])
71 })
72​
73 it('should filter correctly by mutationKey', async () => {
74 const isMutatingArray: Array<number> = []
75 const mutationKey1 = queryKey()
76 const mutationKey2 = queryKey()
77​
78 function IsMutating() {
79 const isMutating = useIsMutating(() => ({ mutationKey: mutationKey1 }))
80​
81 createRenderEffect(() => {
82 isMutatingArray.push(isMutating())
83 })
84​
85 return null
86 }
87​
88 function Page() {
89 const { mutate: mutate1 } = useMutation(() => ({
90 mutationKey: mutationKey1,
91 mutationFn: () => sleep(100).then(() => 'data'),
92 }))
93 const { mutate: mutate2 } = useMutation(() => ({
94 mutationKey: mutationKey2,
95 mutationFn: () => sleep(100).then(() => 'data'),
96 }))
97​
98 createEffect(() => {
99 mutate1()
100 mutate2()
101 })
102​
103 return <IsMutating />
104 }
105​
106 renderWithClient(queryClient, () => <Page />)
107​
108 // Unlike React, IsMutating Wont re-render twice with mutation2
109 await vi.advanceTimersByTimeAsync(100)
110​
111 expect(isMutatingArray).toEqual([0, 1, 0])
112 })
113​
114 it('should filter correctly by predicate', async () => {
115 const isMutatingArray: Array<number> = []
116 const mutationKey1 = queryKey()
117 const mutationKey2 = queryKey()
118​
119 function IsMutating() {
120 const isMutating = useIsMutating(() => ({
121 predicate: (mutation) =>
122 mutation.options.mutationKey?.[0] === mutationKey1[0],
123 }))
124​
125 createRenderEffect(() => {
126 isMutatingArray.push(isMutating())
127 })
128​
129 return null
130 }
131​
132 function Page() {
133 const { mutate: mutate1 } = useMutation(() => ({
134 mutationKey: mutationKey1,
135 mutationFn: () => sleep(100).then(() => 'data'),
136 }))
137 const { mutate: mutate2 } = useMutation(() => ({
138 mutationKey: mutationKey2,
139 mutationFn: () => sleep(100).then(() => 'data'),
140 }))
141​
142 createEffect(() => {
143 mutate1()
144 mutate2()
145 })
146​
147 return <IsMutating />
148 }
149​
150 renderWithClient(queryClient, () => <Page />)
151​
152 // Again, No unnecessary re-renders like React
153 await vi.advanceTimersByTimeAsync(100)
154​
155 expect(isMutatingArray).toEqual([0, 1, 0])
156 })
157​
158 it('should use provided custom queryClient', async () => {
159 const customClient = new QueryClient()
160 const mutationKey1 = queryKey()
161​
162 function Page() {
163 const isMutating = useIsMutating(undefined, () => customClient)
164 const { mutate } = useMutation(
165 () => ({
166 mutationKey: mutationKey1,
167 mutationFn: () => sleep(20).then(() => 'data'),
168 }),
169 () => customClient,
170 )
171​
172 createEffect(() => {
173 setActTimeout(() => {
174 mutate()
175 }, 10)
176 })
177​
178 return (
179 <div>
180 <div>mutating: {isMutating()}</div>
181 </div>
182 )
183 }
184​
185 const rendered = render(() => <Page></Page>)
186​
187 expect(rendered.getByText('mutating: 0')).toBeInTheDocument()
188 await vi.advanceTimersByTimeAsync(10)
189 expect(rendered.getByText('mutating: 1')).toBeInTheDocument()
190 await vi.advanceTimersByTimeAsync(20)
191 expect(rendered.getByText('mutating: 0')).toBeInTheDocument()
192 })
193​
194 it('should resubscribe when a custom queryClient changes', async () => {
195 const queryClient1 = new QueryClient()
196 const queryClient2 = new QueryClient()
197 const [client, setClient] = createSignal(queryClient1)
198 const mutationCache1 = queryClient1.getMutationCache()
199 const originalSubscribe1 = mutationCache1.subscribe.bind(mutationCache1)
200 const unsubscribe1 = vi.fn()
201​
202 vi.spyOn(mutationCache1, 'subscribe').mockImplementation((listener) => {
203 const cleanup = originalSubscribe1(listener)
204​
205 return () => {
206 unsubscribe1()
207 cleanup()
208 }
209 })
210​
211 function Page() {
212 const isMutating = useIsMutating(undefined, client)
213​
214 return <div>mutating: {isMutating()}</div>
215 }
216​
217 const rendered = render(() => <Page />)
218​
219 const firstMutation = queryClient1.getMutationCache().build(queryClient1, {
220 mutationFn: () => sleep(20).then(() => 'data1'),
221 })
222 const firstMutationPromise = firstMutation.execute(undefined)
223​
224 expect(rendered.getByText('mutating: 1')).toBeInTheDocument()
225​
226 setClient(queryClient2)
227​
228 expect(unsubscribe1).toHaveBeenCalledTimes(1)
229 expect(rendered.getByText('mutating: 0')).toBeInTheDocument()
230​
231 const secondMutation = queryClient2.getMutationCache().build(queryClient2, {
232 mutationFn: () => sleep(20).then(() => 'data2'),
233 })
234 const secondMutationPromise = secondMutation.execute(undefined)
235​
236 expect(rendered.getByText('mutating: 1')).toBeInTheDocument()
237​
238 await vi.advanceTimersByTimeAsync(20)
239 await Promise.all([firstMutationPromise, secondMutationPromise])
240​
241 expect(rendered.getByText('mutating: 0')).toBeInTheDocument()
242 })
243​
244 // eslint-disable-next-line vitest/expect-expect
245 it('should not change state if unmounted', async () => {
246 // We have to mock the MutationCache to not unsubscribe
247 // the listener when the component is unmounted
248 class MutationCacheMock extends QueryCore.MutationCache {
249 subscribe(listener: any) {
250 super.subscribe(listener)
251 return () => void 0
252 }
253 }
254​
255 const MutationCacheSpy = vi
256 .spyOn(QueryCore, 'MutationCache')
257 .mockImplementation((fn) => {
258 return new MutationCacheMock(fn)
259 })
260​
261 // Create the client after mocking MutationCache so it uses the mock,
262 // not the centralized client from beforeEach
263 const spiedClient = new QueryClient()
264 const mutationKey1 = queryKey()
265​
266 function IsMutating() {
267 useIsMutating()
268 return null
269 }
270​
271 function Page() {
272 const [mounted, setMounted] = createSignal(true)
273​
274 const { mutate: mutate1 } = useMutation(() => ({
275 mutationKey: mutationKey1,
276 mutationFn: () => sleep(10).then(() => 'data'),
277 }))
278​
279 createEffect(() => {
280 mutate1()
281 })
282​
283 return (
284 <div>
285 <button onClick={() => setMounted(false)}>unmount</button>
286 <Show when={mounted()}>
287 <IsMutating />
288 </Show>
289 </div>
290 )
291 }
292​
293 const rendered = renderWithClient(spiedClient, () => <Page />)
294​
295 fireEvent.click(rendered.getByText('unmount'))
296​
297 // Should not display the console error
298 // "Warning: Can't perform a React state update on an unmounted component"
299​
300 await vi.advanceTimersByTimeAsync(20)
301 MutationCacheSpy.mockRestore()
302 })
303})