Skip to content

Commit

Permalink
test: debounce
Browse files Browse the repository at this point in the history
  • Loading branch information
gabrieljablonski committed Feb 18, 2024
1 parent ceb1d95 commit 76dcf30
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 9 deletions.
42 changes: 34 additions & 8 deletions src/test/utils.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,22 +62,48 @@ describe('compute positions', () => {
describe('debounce', () => {
jest.useFakeTimers()

let func
let debouncedFunc

beforeEach((timeout = 1000) => {
func = jest.fn()
debouncedFunc = debounce(func, timeout)
})
const func = jest.fn()

test('execute just once', () => {
const debouncedFunc = debounce(func, 1000)
for (let i = 0; i < 100; i += 1) {
debouncedFunc()
}

// Fast-forward time
expect(func).not.toHaveBeenCalled()

jest.runAllTimers()

expect(func).toBeCalledTimes(1)
})

test('execute immediately just once', () => {
const debouncedFunc = debounce(func, 1000, true)

debouncedFunc()
expect(func).toBeCalledTimes(1)

for (let i = 0; i < 100; i += 1) {
debouncedFunc()
}

jest.runAllTimers()

expect(func).toHaveBeenCalledTimes(1)
})

test('does not execute after cancel', () => {
const debouncedFunc = debounce(func, 1000)

debouncedFunc()

expect(func).not.toHaveBeenCalled()

debouncedFunc.cancel()

jest.runAllTimers()

expect(func).not.toHaveBeenCalled()
})
})
})
4 changes: 3 additions & 1 deletion src/utils/debounce.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const debounce = <T, A extends any[]>(

if (immediate && !timeout) {
/**
* there's not need to clear the timeout
* there's no need to clear the timeout
* since we expect it to resolve and set `timeout = null`
*/
func.apply(this, args)
Expand All @@ -38,9 +38,11 @@ const debounce = <T, A extends any[]>(
}

debounced.cancel = () => {
/* c8 ignore start */
if (!timeout) {
return
}
/* c8 ignore end */
clearTimeout(timeout)
timeout = null
}
Expand Down

0 comments on commit 76dcf30

Please sign in to comment.