Files
health-record-mp/src/utils/debounce.test.ts
2026-08-20 15:26:19 +08:00

60 lines
1.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { debounce } from './debounce'
describe('debounce', () => {
beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
})
it('trailing edge默认多次调用后只触发一次使用最后一次的参数', () => {
const fn = vi.fn()
const debouncedFn = debounce(fn, 100)
debouncedFn('first')
debouncedFn('second')
debouncedFn('last')
expect(fn).not.toHaveBeenCalled()
vi.advanceTimersByTime(100)
expect(fn).toHaveBeenCalledTimes(1)
expect(fn).toHaveBeenCalledWith('last')
})
it('cancel取消后计时器到期不执行', () => {
const fn = vi.fn()
const debouncedFn = debounce(fn, 100)
debouncedFn()
debouncedFn.cancel()
vi.advanceTimersByTime(100)
expect(fn).not.toHaveBeenCalled()
})
it('flush立即执行待执行的调用并传递参数', () => {
const fn = vi.fn()
const debouncedFn = debounce(fn, 100)
debouncedFn('arg1')
debouncedFn.flush()
expect(fn).toHaveBeenCalledWith('arg1')
})
it('leading edge第一次调用立即执行', () => {
const fn = vi.fn()
const debouncedFn = debounce(fn, 100, { edges: ['leading'] })
debouncedFn()
expect(fn).toHaveBeenCalledTimes(1)
})
})