Files

106 lines
2.5 KiB
TypeScript

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { debounce } from '../../../src/lib/utils/debounce';
describe('debounce', () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.restoreAllMocks();
});
it('delays function execution', () => {
const fn = vi.fn();
const debouncedFn = debounce(fn, 100);
debouncedFn();
expect(fn).not.toHaveBeenCalled();
vi.advanceTimersByTime(100);
expect(fn).toHaveBeenCalledTimes(1);
});
it('cancels previous calls when called multiple times', () => {
const fn = vi.fn();
const debouncedFn = debounce(fn, 100);
debouncedFn();
vi.advanceTimersByTime(50);
debouncedFn();
vi.advanceTimersByTime(50);
debouncedFn();
expect(fn).not.toHaveBeenCalled();
vi.advanceTimersByTime(100);
expect(fn).toHaveBeenCalledTimes(1);
});
it('passes arguments correctly', () => {
const fn = vi.fn();
const debouncedFn = debounce(fn, 100);
debouncedFn('arg1', 'arg2', 123);
vi.advanceTimersByTime(100);
expect(fn).toHaveBeenCalledWith('arg1', 'arg2', 123);
});
it('uses latest arguments when called multiple times', () => {
const fn = vi.fn();
const debouncedFn = debounce(fn, 100);
debouncedFn('first');
vi.advanceTimersByTime(50);
debouncedFn('second');
vi.advanceTimersByTime(50);
debouncedFn('third');
vi.advanceTimersByTime(100);
expect(fn).toHaveBeenCalledTimes(1);
expect(fn).toHaveBeenCalledWith('third');
});
it('allows multiple independent debounced functions', () => {
const fn1 = vi.fn();
const fn2 = vi.fn();
const debouncedFn1 = debounce(fn1, 100);
const debouncedFn2 = debounce(fn2, 100);
debouncedFn1('fn1');
debouncedFn2('fn2');
vi.advanceTimersByTime(100);
expect(fn1).toHaveBeenCalledWith('fn1');
expect(fn2).toHaveBeenCalledWith('fn2');
});
it('works with different delay times', () => {
const fn = vi.fn();
const debouncedFn = debounce(fn, 500);
debouncedFn();
vi.advanceTimersByTime(100);
expect(fn).not.toHaveBeenCalled();
vi.advanceTimersByTime(400);
expect(fn).toHaveBeenCalledTimes(1);
});
it('clears timeout properly after execution', () => {
const fn = vi.fn();
const debouncedFn = debounce(fn, 100);
debouncedFn();
vi.advanceTimersByTime(100);
expect(fn).toHaveBeenCalledTimes(1);
debouncedFn();
vi.advanceTimersByTime(100);
expect(fn).toHaveBeenCalledTimes(2);
});
});