首页 > 解决方案 > 对去抖函数进行单元测试以查看计时器是否在 500 毫秒后超时

问题描述

  export const debounce = (func: (arg?: any) => void, timeOut: number = 500) => {
      let timer: ReturnType<typeof setTimeout>;
      return function(...args: any) {
        if (timer) clearTimeout(timer);
        timer = setTimeout(func, timeOut, ...args);
      };
    };

我正在尝试为此去抖动功能创建一个简单的测试。我该如何开始?

标签: javascriptjestjs

解决方案


我们可以模拟计时器jest.useFakeTimers();

我们可以确保我们的函数只有在超时后才被调用:

jest.useFakeTimers();

it('calls function after 500ms if timeout not been specified', () => {
  const callback = jest.fn();
  const debounced = debounce(callback);
  debounced();
  expect(callback).not.toHaveBeenCalled();
  jest.advanceTimersByTime(499);
  expect(callback).not.toHaveBeenCalled();
  jest.advanceTimersByTime(2);
  expect(callback).toHaveBeenCalled();
});

此外,您可能需要检查底层函数是否获得与您传递给去抖动版本相同的参数

it('passes same arguments down to callback', () => {
  const callback = jest.fn();
  const debounced = debounce(callback, 1);
  debounced(1, 'a');
  jest.advanceTimersByTime(2);
  expect(callback).toHaveBeenCalledWith(1, 'a');
});

顺序调用会改变回调执行:

it('each call delay execution for specified timeout', () => {
  const callback = jest.fn();
  const debounced = debounce(callback, 50);
  debounced();
  jest.advanceTimersByTime(49);
  debounced();
  expect(callback).not.toHaveBeenCalled();
  jest.advanceTimersByTime(49);
  expect(callback).not.toHaveBeenCalled();
  jest.advanceTimersByTime(2);
  expect(callback).toHaveBeenCalled();
});


推荐阅读