Skip to content

Commit

Permalink
feat: add useDebounceFn
Browse files Browse the repository at this point in the history
  • Loading branch information
lmhcoding committed Sep 21, 2020
1 parent 7bcd64c commit 5f01102
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.ts
Expand Up @@ -17,3 +17,4 @@ export * from './useHistory'
export * from './useTimeout'
export * from './useTimeoutFn'
export * from './useDebounce'
export * from './useDebounceFn'
13 changes: 13 additions & 0 deletions src/useDebounceFn.ts
@@ -0,0 +1,13 @@
import { watch } from 'vue'
import { useDebounce } from './useDebounce'

export function useDebounceFn(fn: Function, delay = 200) {
const debounceValue = useDebounce(0, delay)

watch(debounceValue, () => {
fn()
})
return () => {
debounceValue.value++
}
}
43 changes: 43 additions & 0 deletions tests/useDebounceFn.test.ts
@@ -0,0 +1,43 @@
import { nextTick } from 'vue'
import { useDebounceFn } from '../src/useDebounceFn'

let callback: Function | null

beforeEach(() => {
jest.useFakeTimers()
callback = jest.fn()
})

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()
jest.advanceTimersByTime(200)
await nextTick()
expect(callback!).toHaveBeenCalledTimes(1)
})

0 comments on commit 5f01102

Please sign in to comment.