使用Jasmine的异步函数的规范

时间:2012-12-04 16:09:00

标签: underscore.js jasmine

当我尝试使用jasmine在_.debounce function中测试this qunit test时会发生一些奇怪的事情。

似乎可以使用jasmine.Clock.useMock()来测试... 但是当我写道:

it('_.debounce()', function () {
    var spy = jasmine.createSpy('debounce'),
        debouncedSpy = _.debounce(spy, 100);

    jasmine.Clock.useMock();

    // direct calls
    debouncedSpy();
    debouncedSpy();
    debouncedSpy();

    // timed out calls
    setTimeout(debouncedSpy, 60);
    setTimeout(debouncedSpy, 120);
    setTimeout(debouncedSpy, 180);
    setTimeout(debouncedSpy, 240);
    setTimeout(debouncedSpy, 300);

    jasmine.Clock.tick(300);
    expect(spy).toHaveBeenCalled();

    jasmine.Clock.tick(400);
    expect(spy).toHaveBeenCalled();

    jasmine.Clock.tick(1000);
    expect(spy.callCount).toBe(1);
});

它不起作用(呼叫计数等于3)。但是没有直接调用(或者当我使用setTimeout(..., 0)时)一切正常。我做错了什么?

此外,我尝试通过runswaits进行此操作,并且可行。但为什么它在前面的例子中不起作用?

it('should be called once', function () {
    var spy = jasmine.createSpy('debounce'),
        debouncedSpy = _.debounce(spy, 100);

    runs(function () {
        debouncedSpy();
        debouncedSpy();
        debouncedSpy();

        expect(spy).not.toHaveBeenCalled();

        setTimeout(debouncedSpy, 60);
        setTimeout(debouncedSpy, 120);
        setTimeout(debouncedSpy, 180);
        setTimeout(debouncedSpy, 240);
        setTimeout(debouncedSpy, 300);
    });

    waits(800);

    runs(function () {
        expect(spy.callCount).toBe(1);
    });
});

2 个答案:

答案 0 :(得分:4)

https://github.com/pivotal/jasmine/issues/361https://github.com/pivotal/jasmine/pull/455之前。释放后,您将此添加到测试中以使Jasmine跳过去抖延迟。

_.debounce = function (func) { return function () { func.apply(this, arguments);}; };

答案 1 :(得分:2)

茉莉花模拟时钟只会改变setTimeout的行为,它目前不会模仿Date,请参阅https://github.com/pivotal/jasmine/issues/361https://github.com/pivotal/jasmine/pull/455。使用runswaitsFor(或在jasmine 2.0 done回调中),实际上让时间过去,以便浏览器实际更改Date值,以便在{{}}内发生日期数学运算{1}}加起来。