如何为原型中的 setinterval 编写 jasmine 测试
how to write a jasmine test for a setinterval inside a prototype
我想为我的 setInterval 编写一个测试,并测试警报 window 是否已用值 'pulse' 触发。我该怎么做呢?我已经尝试了很多变体,但似乎无法弄清楚。我已经提供了代码和我的规范文件。我正在使用茉莉花 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();
});
});
您想使用茉莉花时钟(它挂接真实时钟并允许您根据需要模拟时间)。
查看 jasmine 帮助 - 那里的示例几乎完全符合您的要求。 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();
我想为我的 setInterval 编写一个测试,并测试警报 window 是否已用值 'pulse' 触发。我该怎么做呢?我已经尝试了很多变体,但似乎无法弄清楚。我已经提供了代码和我的规范文件。我正在使用茉莉花 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();
});
});
您想使用茉莉花时钟(它挂接真实时钟并允许您根据需要模拟时间)。
查看 jasmine 帮助 - 那里的示例几乎完全符合您的要求。 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();