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