Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
2import { waitFor } from '@testing-library/react'
3import { MutationObserver } from '..'
4import { createQueryClient, sleep } from './utils'
5import type { QueryClient } from '..'
6β
7describe('mutationObserver', () => {
8 let queryClient: QueryClient
9β
10 beforeEach(() => {
11 queryClient = createQueryClient()
12 queryClient.mount()
13 })
14β
15 afterEach(() => {
16 queryClient.clear()
17 })
18β
19 test('onUnsubscribe should not remove the current mutation observer if there is still a subscription', async () => {
20 const mutation = new MutationObserver(queryClient, {
21 mutationFn: async (text: string) => {
22 await sleep(20)
23 return text
24 },
25 })
26β
27 const subscription1Handler = vi.fn()
28 const subscription2Handler = vi.fn()
29β
30 const unsubscribe1 = mutation.subscribe(subscription1Handler)
31 const unsubscribe2 = mutation.subscribe(subscription2Handler)
32β
33 mutation.mutate('input')
34β
35 unsubscribe1()
36β
37 await waitFor(() => {
38 // 1 call: loading
39 expect(subscription1Handler).toBeCalledTimes(1)
40 // 2 calls: loading, success
41 expect(subscription2Handler).toBeCalledTimes(2)
42 })
43β
44 // Clean-up
45 unsubscribe2()
46 })
47})