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

mutationObserver.test.tsx

76 lines2.0 KB

1import { waitFor } from '@testing-library/react'
2import { MutationObserver } from '..'
3import { createQueryClient, sleep } from './utils'
4import type { QueryClient } from '..'
5​
6describe('mutationObserver', () => {
7 let queryClient: QueryClient
8​
9 beforeEach(() => {
10 queryClient = createQueryClient()
11 queryClient.mount()
12 })
13​
14 afterEach(() => {
15 queryClient.clear()
16 })
17​
18 test('onUnsubscribe should not remove the current mutation observer if there is still a subscription', async () => {
19 const mutation = new MutationObserver(queryClient, {
20 mutationFn: async (text: string) => {
21 await sleep(20)
22 return text
23 },
24 })
25​
26 const subscription1Handler = jest.fn()
27 const subscription2Handler = jest.fn()
28​
29 const unsubscribe1 = mutation.subscribe(subscription1Handler)
30 const unsubscribe2 = mutation.subscribe(subscription2Handler)
31​
32 mutation.mutate()
33​
34 unsubscribe1()
35​
36 await waitFor(() => {
37 // 1 call: loading
38 expect(subscription1Handler).toBeCalledTimes(1)
39 // 2 calls: loading, success
40 expect(subscription2Handler).toBeCalledTimes(2)
41 })
42​
43 // Clean-up
44 unsubscribe2()
45 })
46​
47 test('should not notify listeners if options.listeners is set to false', async () => {
48 const mutation = new MutationObserver(queryClient, {
49 mutationFn: async (text: string) => {
50 await sleep(20)
51 return text
52 },
53 })
54​
55 const subscriptionHandler = jest.fn()
56 const unsubscribe = mutation.subscribe(subscriptionHandler)
57 mutation.mutate()
58​
59 await waitFor(() => {
60 // 2 calls: loading, success
61 expect(subscriptionHandler).toBeCalledTimes(2)
62 })
63 subscriptionHandler.mockReset()
64​
65 // Force a notification with listeners set to false
66 // because there is no existing usage of notify with listeners set to false
67 mutation['notify']({ listeners: false })
68​
69 await waitFor(() => {
70 // 0 call because no notification has been sent
71 expect(subscriptionHandler).toBeCalledTimes(0)
72 })
73​
74 unsubscribe()
75 })
76})