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

useIsMutating.test.tsx

302 lines8.3 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 { createKey, 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 = createKey()
25 const mutationKey2 = createKey()
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 mutation1 = useMutation(() => ({
39 mutationKey: mutationKey1,
40 mutationFn: () => sleep(150).then(() => 'data'),
41 }))
42 const mutation2 = useMutation(() => ({
43 mutationKey: mutationKey2,
44 mutationFn: () => sleep(50).then(() => 'data'),
45 }))
46​
47 createEffect(() => {
48 mutation1.mutate()
49 setActTimeout(() => {
50 mutation2.mutate()
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 expect(isMutatingArray).toStrictEqual([0, 1, 2, 1, 0])
70 })
71​
72 it('should filter correctly by mutationKey', async () => {
73 const isMutatingArray: Array<number> = []
74 const mutationKey1 = createKey()
75 const mutationKey2 = createKey()
76​
77 function IsMutating() {
78 const isMutating = useIsMutating(() => ({ mutationKey: mutationKey1 }))
79​
80 createRenderEffect(() => {
81 isMutatingArray.push(isMutating())
82 })
83​
84 return null
85 }
86​
87 function Page() {
88 const mutation1 = useMutation(() => ({
89 mutationKey: mutationKey1,
90 mutationFn: () => sleep(100).then(() => 'data'),
91 }))
92 const mutation2 = useMutation(() => ({
93 mutationKey: mutationKey2,
94 mutationFn: () => sleep(100).then(() => 'data'),
95 }))
96​
97 createEffect(() => {
98 mutation1.mutate()
99 mutation2.mutate()
100 })
101​
102 return <IsMutating />
103 }
104​
105 renderWithClient(queryClient, () => <Page />)
106​
107 // Unlike React, IsMutating Wont re-render twice with mutation2
108 await vi.advanceTimersByTimeAsync(100)
109 expect(isMutatingArray).toStrictEqual([0, 1, 0])
110 })
111​
112 it('should filter correctly by predicate', async () => {
113 const isMutatingArray: Array<number> = []
114 const mutationKey1 = createKey()
115 const mutationKey2 = createKey()
116​
117 function IsMutating() {
118 const isMutating = useIsMutating(() => ({
119 predicate: (mutation) =>
120 mutation.options.mutationKey?.[0] === mutationKey1[0],
121 }))
122​
123 createRenderEffect(() => {
124 isMutatingArray.push(isMutating())
125 })
126​
127 return null
128 }
129​
130 function Page() {
131 const mutation1 = useMutation(() => ({
132 mutationKey: mutationKey1,
133 mutationFn: () => sleep(100).then(() => 'data'),
134 }))
135 const mutation2 = useMutation(() => ({
136 mutationKey: mutationKey2,
137 mutationFn: () => sleep(100).then(() => 'data'),
138 }))
139​
140 createEffect(() => {
141 mutation1.mutate()
142 mutation2.mutate()
143 })
144​
145 return <IsMutating />
146 }
147​
148 renderWithClient(queryClient, () => <Page />)
149​
150 // Again, No unnecessary re-renders like React
151 await vi.advanceTimersByTimeAsync(100)
152 expect(isMutatingArray).toStrictEqual([0, 1, 0])
153 })
154​
155 it('should use provided custom queryClient', async () => {
156 const customClient = new QueryClient()
157 const mutationKey1 = createKey()
158​
159 function Page() {
160 const isMutating = useIsMutating(undefined, () => customClient)
161 const mutation = useMutation(
162 () => ({
163 mutationKey: mutationKey1,
164 mutationFn: () => sleep(20).then(() => 'data'),
165 }),
166 () => customClient,
167 )
168​
169 createEffect(() => {
170 setActTimeout(() => {
171 mutation.mutate()
172 }, 10)
173 })
174​
175 return (
176 <div>
177 <div>mutating: {isMutating()}</div>
178 </div>
179 )
180 }
181​
182 const rendered = render(() => <Page />)
183​
184 expect(rendered.getByText('mutating: 0')).toBeInTheDocument()
185 await vi.advanceTimersByTimeAsync(10)
186 expect(rendered.getByText('mutating: 1')).toBeInTheDocument()
187 await vi.advanceTimersByTimeAsync(20)
188 expect(rendered.getByText('mutating: 0')).toBeInTheDocument()
189 })
190​
191 it('should resubscribe when a custom queryClient changes', async () => {
192 const queryClient1 = new QueryClient()
193 const queryClient2 = new QueryClient()
194 const [client, setClient] = createSignal(queryClient1)
195 const mutationCache1 = queryClient1.getMutationCache()
196 const originalSubscribe1 = mutationCache1.subscribe.bind(mutationCache1)
197 const unsubscribe1 = vi.fn<() => void>()
198​
199 vi.spyOn(mutationCache1, 'subscribe').mockImplementation((listener) => {
200 const cleanup = originalSubscribe1(listener)
201​
202 return () => {
203 unsubscribe1()
204 cleanup()
205 }
206 })
207​
208 function Page() {
209 const isMutating = useIsMutating(undefined, client)
210​
211 return <div>mutating: {isMutating()}</div>
212 }
213​
214 const rendered = render(() => <Page />)
215​
216 const firstMutation = queryClient1.getMutationCache().build(queryClient1, {
217 mutationFn: () => sleep(20).then(() => 'data1'),
218 })
219 const firstMutationPromise = firstMutation.execute(undefined)
220​
221 expect(rendered.getByText('mutating: 1')).toBeInTheDocument()
222​
223 setClient(queryClient2)
224 expect(unsubscribe1).toHaveBeenCalledTimes(1)
225 expect(rendered.getByText('mutating: 0')).toBeInTheDocument()
226​
227 const secondMutation = queryClient2.getMutationCache().build(queryClient2, {
228 mutationFn: () => sleep(20).then(() => 'data2'),
229 })
230 const secondMutationPromise = secondMutation.execute(undefined)
231​
232 expect(rendered.getByText('mutating: 1')).toBeInTheDocument()
233 await vi.advanceTimersByTimeAsync(20)
234 await Promise.all([firstMutationPromise, secondMutationPromise])
235 expect(rendered.getByText('mutating: 0')).toBeInTheDocument()
236 })
237​
238 it('should not change state if unmounted', async () => {
239 const states: Array<number> = []
240 // We have to mock the MutationCache to not unsubscribe
241 // the listener when the component is unmounted
242 class MutationCacheMock extends QueryCore.MutationCache {
243 override subscribe(listener: any) {
244 super.subscribe(listener)
245 return () => void 0
246 }
247 }
248​
249 vi.spyOn(QueryCore, 'MutationCache').mockImplementation((fn) => {
250 return new MutationCacheMock(fn)
251 })
252​
253 // Create the client after mocking MutationCache so it uses the mock,
254 // not the centralized client from beforeEach
255 const spiedClient = new QueryClient()
256 const mutationKey1 = createKey()
257​
258 function IsMutating() {
259 const isMutating = useIsMutating()
260 createRenderEffect(() => {
261 states.push(isMutating())
262 })
263 return null
264 }
265​
266 function Page() {
267 const [mounted, setMounted] = createSignal(true)
268​
269 const mutation1 = useMutation(() => ({
270 mutationKey: mutationKey1,
271 mutationFn: () => sleep(10).then(() => 'data'),
272 }))
273​
274 createEffect(() => {
275 mutation1.mutate()
276 })
277​
278 return (
279 <div>
280 <button onClick={() => setMounted(false)}>unmount</button>
281 <Show when={mounted()}>
282 <IsMutating />
283 </Show>
284 </div>
285 )
286 }
287​
288 const rendered = renderWithClient(spiedClient, () => <Page />)
289 expect(states).toStrictEqual([0, 1])
290​
291 fireEvent.click(rendered.getByText('unmount'))
292 expect(spiedClient.getMutationCache().getAll()[0]?.state.status).toBe(
293 'pending',
294 )
295​
296 await vi.advanceTimersByTimeAsync(20)
297 expect(spiedClient.getMutationCache().getAll()[0]?.state.status).toBe(
298 'success',
299 )
300 expect(states).toStrictEqual([0, 1])
301 })
302})