【问题标题】:Custom throttle unit test自定义油门单元测试
【发布时间】:2021-02-24 13:51:44
【问题描述】:

我有以下测试:

import { throttle } from "./event";

jest.useFakeTimers();

it('mock setTimeout test', () => {
    const mockedFunction = jest.fn();
    throttle(mockedFunction, 1);
    expect(setTimeout).toHaveBeenLastCalledWith(mockedFunction, 1000);
    expect(setTimeout).toHaveBeenCalledTimes(1);
});

油门在哪里:

export const throttle = (func, wait) => {
    let timer = null;
    return function(...args) {
        if (timer === null) {
            timer = setTimeout(() => {
                func.apply(this, args);
                timer = null;
            }, wait); 
        }
    };
};

但测试失败:

【问题讨论】:

    标签: javascript unit-testing jestjs


    【解决方案1】:

    错误就在这里,throttle 会为你创建一个新函数,“添加”一个“等待之前”功能......你从来没有调用过它

      throttle(mockedFunction, 1)();
    

    【讨论】:

      猜你喜欢
      • 2011-11-05
      • 2020-08-15
      • 2018-02-25
      • 2015-01-11
      • 1970-01-01
      • 2012-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多