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

notifyManager.test.tsx

85 lines2.6 KB

1import { describe, expect, it, vi } from 'vitest'
2import { createNotifyManager } from '../notifyManager'
3import { sleep } from './utils'
4​
5describe('notifyManager', () => {
6 it('should use default notifyFn', async () => {
7 const notifyManagerTest = createNotifyManager()
8 const callbackSpy = vi.fn()
9 notifyManagerTest.schedule(callbackSpy)
10 await sleep(1)
11 expect(callbackSpy).toHaveBeenCalled()
12 })
13​
14 it('should use default batchNotifyFn', async () => {
15 const notifyManagerTest = createNotifyManager()
16 const callbackScheduleSpy = vi
17 .fn()
18 .mockImplementation(async () => await sleep(20))
19 const callbackBatchLevel2Spy = vi.fn().mockImplementation(async () => {
20 notifyManagerTest.schedule(callbackScheduleSpy)
21 })
22 const callbackBatchLevel1Spy = vi.fn().mockImplementation(async () => {
23 notifyManagerTest.batch(callbackBatchLevel2Spy)
24 })
25​
26 notifyManagerTest.batch(callbackBatchLevel1Spy)
27​
28 await sleep(30)
29 expect(callbackBatchLevel1Spy).toHaveBeenCalledTimes(1)
30 expect(callbackBatchLevel2Spy).toHaveBeenCalledTimes(1)
31 expect(callbackScheduleSpy).toHaveBeenCalledTimes(1)
32 })
33​
34 it('should use a custom scheduler when configured', async () => {
35 const customCallback = vi.fn((cb) => queueMicrotask(cb))
36​
37 const notifyManagerTest = createNotifyManager()
38 const notifySpy = vi.fn()
39 notifyManagerTest.setScheduler(customCallback)
40 notifyManagerTest.setNotifyFunction(notifySpy)
41​
42 notifyManagerTest.batch(() => notifyManagerTest.schedule(vi.fn))
43​
44 expect(customCallback).toHaveBeenCalledOnce()
45​
46 // wait until the microtask has run
47 await new Promise<void>((res) => queueMicrotask(res))
48​
49 expect(notifySpy).toHaveBeenCalledTimes(1)
50 })
51​
52 it('should notify if error is thrown', async () => {
53 const notifyManagerTest = createNotifyManager()
54 const notifySpy = vi.fn()
55​
56 notifyManagerTest.setNotifyFunction(notifySpy)
57​
58 try {
59 notifyManagerTest.batch(() => {
60 notifyManagerTest.schedule(vi.fn)
61 throw new Error('Foo')
62 })
63 } catch {}
64​
65 // needed for setTimeout to kick in
66 await sleep(1)
67​
68 expect(notifySpy).toHaveBeenCalledTimes(1)
69 })
70​
71 it('typeDefs should catch proper signatures', async () => {
72 const notifyManagerTest = createNotifyManager()
73​
74 // we define some fn with its signature:
75 const fn: (a: string, b: number) => string = (a, b) => a + b
76​
77 //now someFn expect to be called with args [a: string, b: number]
78 const someFn = notifyManagerTest.batchCalls(fn)
79​
80 someFn('im happy', 4)
81​
82 //@ts-expect-error
83 someFn('im not happy', false)
84 })
85})