当我尝试使用 jasmine在这个 qunit 测试中测试_.debounce 函数时,会发生一些奇怪的事情。
似乎可以使用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)
),一切正常。我做错了什么?
我也尝试通过runs
and来完成它waits
,并且它有效。但为什么它在前面的例子中不起作用?
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);
});
});