-
Notifications
You must be signed in to change notification settings - Fork 14
/
useDebounceFn.test.ts
47 lines (40 loc) · 1.32 KB
/
useDebounceFn.test.ts
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
import { nextTick } from 'vue'
import { useDebounceFn } from '../src/useDebounceFn'
let callback: (...rest: any[]) => any
beforeEach(() => {
jest.useFakeTimers()
callback = jest.fn((s: string) => {
console.log(s)
})
})
afterEach(() => {
jest.useRealTimers()
jest.clearAllMocks()
})
test('callback should not be called after invoking useDebounceFn', () => {
useDebounceFn(callback!)
expect(callback!).not.toBeCalled()
})
test('setTimeout should be called after invoking the function returned by useDebounceFn', () => {
const debounceFn = useDebounceFn(callback!)
debounceFn()
expect(setTimeout).toHaveBeenCalledTimes(1)
expect(setTimeout).toHaveBeenCalledWith(expect.any(Function), 200)
})
test('timer should be cleared when calling the function returned by useDebounceFn in 200s', () => {
const debounceFn = useDebounceFn(callback!)
debounceFn()
debounceFn()
expect(clearTimeout).toHaveBeenCalledTimes(1)
expect(setTimeout).toHaveBeenCalledTimes(2)
expect(setTimeout).toHaveBeenCalledWith(expect.any(Function), 200)
})
test('callback should be called when timeout', async () => {
const debounceFn = useDebounceFn(callback!)
debounceFn('1')
debounceFn('2')
jest.advanceTimersByTime(200)
await nextTick()
expect(callback!).toHaveBeenCalledTimes(1)
expect(callback!).toHaveBeenCalledWith('2')
})