Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 47 additions & 1 deletion libs/common-utils/src/misc.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,50 @@
import { isRejectRequestProviderError, TimeoutError, withTimeout } from './misc'
import { debounce, isRejectRequestProviderError, TimeoutError, withTimeout } from './misc'

describe('debounce', () => {
beforeEach(() => {
jest.useFakeTimers()
})

afterEach(() => {
jest.useRealTimers()
})

it('forwards the original arguments to the wrapped function', () => {
const func = jest.fn()
const debounced = debounce(func, 100)

debounced('/swap?chain=mainnet', ['param'], 'CoW Swap')
jest.advanceTimersByTime(100)

// Regression: the wrapped function used to receive a single array argument
// (['/swap?chain=mainnet', ['param'], 'CoW Swap']) instead of the original arguments
expect(func).toHaveBeenCalledTimes(1)
expect(func).toHaveBeenCalledWith('/swap?chain=mainnet', ['param'], 'CoW Swap')
})

it('invokes the wrapped function only once with the latest arguments', () => {
const func = jest.fn()
const debounced = debounce(func, 100)

debounced('first')
jest.advanceTimersByTime(50)
debounced('second')
jest.advanceTimersByTime(100)

expect(func).toHaveBeenCalledTimes(1)
expect(func).toHaveBeenCalledWith('second')
})

it('does not invoke the wrapped function before the wait time elapses', () => {
const func = jest.fn()
const debounced = debounce(func, 100)

debounced()
jest.advanceTimersByTime(99)

expect(func).not.toHaveBeenCalled()
})
})

describe('withTimeout', () => {
it('resolves when the promise settles before the timeout', async () => {
Expand Down
2 changes: 1 addition & 1 deletion libs/common-utils/src/misc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export function debounce<F extends (...args: any) => any>(func: F, wait = 200) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-function-return-type
const debounced = (...args: any) => {
clearTimeout(timeout)
timeout = setTimeout(() => func(args), wait)
timeout = setTimeout(() => func(...args), wait)
}

return debounced
Expand Down
Loading