我想为我的setInterval编写一个测试,并测试警告窗口是否以值'pulse'触发。我该怎么做呢?我已经尝试了很多这方面的变化,但似乎无法弄清楚这一点。我已经提供了代码和我的spec文件。我正在使用茉莉花2.0。任何帮助表示赞赏。
countTimer.js
function CountTimer(timelength){
this.timelength = timelength;
this.running = false;
}
CountTimer.prototype.start = function(){
this.running = true;
setInterval(function () {alert('pulse')}, 2000);
};
CountTimer.prototype.stop = function(){
this.running = false;
};
countTimerSpec.js
describe("Timer",function() {
var myTimer;
beforeEach(function() {
myTimer = new CountTimer(25);
});
...
it("start should run setInterval 'pulse' every 2 seconds via setInterval", function(){
myTimer.start();
//what goes here???
expect(sut.callback).toHaveBeenCalled();
});
});
答案 0 :(得分:1)
你想使用茉莉花钟(它挂钩真正的时钟,让你可以根据需要模拟时间)。
检查茉莉花的帮助 - 这个例子几乎就是你要做的事情。 http://jasmine.github.io/2.3/introduction.html
基本步骤(在您的测试中):
jasmine.clock().install();
myTimer.start();
jasmine.clock().tick(2001); //enough that your interval gets tripped
expect(...)
jasmine.clock().uninstall();