Open History to see the last commit
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})