javascript - 测试使用 setTimeout 和 Jest : why is this test failing? 的函数

标签 javascript unit-testing jestjs

我有一个 rateLimit 函数(它只是 this code 的修改版本):

function rateLimit(func, wait) {
    var timeout;
    return function () {
        var context = this;
        var args = arguments;
        var later = function () {
            timeout = null;
            func.apply(context, args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

此功能在我的应用程序中运行良好,所以我相当确定实现是好的。但是,以下测试失败:

jest.useFakeTimers();

test('rateLimit', () => {
    const action = jest.fn();

    const doAction = rateLimit(action, 100);

    doAction(); // This should increment the call count
    doAction(); // This shouldn't, because 100ms hasn't elapsed yet

    jest.advanceTimersByTime(101);

    doAction(); // This should increment the count again

    expect(action).toHaveBeenCalledTimes(2);
});

出现错误:

Expected mock function to have been called two times, but it was called one time.

Here is a runnable version of this code on repl.it .

我在这里做错了什么?

最佳答案

您的速率限制器使用 trailing 方法,当新调用进入时,它会取消当前正在进行的任何调用...直到等待时间到期,此时函数被调用。

您只需要再次提前计时器以便再次调用该函数:

jest.useFakeTimers();

test('rateLimit', () => {
    const action = jest.fn();

    const doAction = rateLimit(action, 100);

    doAction(); // This should increment the call count
    doAction(); // This shouldn't, because 100ms hasn't elapsed yet

    jest.advanceTimersByTime(101);

    doAction(); // This should increment the count again

    jest.advanceTimersByTime(101);  // <= advance the timers again

    expect(action).toHaveBeenCalledTimes(2);  // Success!
});

关于javascript - 测试使用 setTimeout 和 Jest : why is this test failing? 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55371237/

相关文章:

javascript - 来自 Ember 数据的模型未渲染

unit-testing - 你如何在 TCl 中测试私有(private)方法

html - Create React App提供的react-scripts包需要依赖: Babel-Jest

javascript - 如何在使用 jest 和 react-testing-library 进行测试时设置组件的本地状态?

javascript - jQuery on Change 引用 this.value 和 this

javascript - ng-bind-html 不处理输入

php - 我如何在 PHP 旁边使用 HTML5 本地存储,将其用于 php session ,并存储 php 使用的其他信息

unit-testing - XCTAssertEqual 与 Optional(不是 Equatable)

php - 使用 vfsStream 将文件插入特定目录/节点

javascript - 未找到使用 grunt 运行 jest 的测试