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