javascript – 如何为setInterval()函数编写测试用例
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 如何为setInterval()函数编写测试用例,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1776字,纯文字阅读大概需要3分钟。
内容图文
![javascript – 如何为setInterval()函数编写测试用例](/upload/InfoBanner/zyjiaocheng/827/300ca260a725415a9d80a7a05e8ae37f.jpg)
我有一个计时器,并假设当计数器计数到3时将执行特定的功能.
var a_interval_function = function(){
var counter = 1;
var interval = setInterval(function(){
if(counter === 5){
clearInterval(interval);
}
// run the function when the counter is 3
if(counter === 3){
a_function_should_be_runned();
}
counter++;
}, 500);
return interval;
}
但是,我不知道如何建立一个有效的测试用例来测试计数器以及执行函数的时间.有谁知道怎么做?类似于以下内容:
// and some test case like this
it('a timer test', function(done){
var interval = a_interval_function();
expect(a_function_should_be_runned.state).to.equal({
name: 'runned',
counter: 3,
time: 300,
});
});
谢谢.
解决方法:
也许你可以使用sinon.useFakeTimers().
例如:
var sinon = require('sinon');
var expect = require('chai').expect;
var a_function_should_be_runned = sinon.spy();
var a_interval_function = function(){
var counter = 1;
var interval = setInterval(function(){
if(counter === 5){
clearInterval(interval);
}
// run the function when the counter is 3
if(counter === 3){
a_function_should_be_runned();
}
counter++;
}, 500);
return interval;
}
describe('timer tests', function() {
before(function() {
this.clock = sinon.useFakeTimers();
});
after(function() {
this.clock.restore();
});
it('a timer test', function() {
var interval = a_interval_function();
// At time 0, we don't expect the function to have been called.
expect(a_function_should_be_runned.called).to.be.false;
// Advance clock 500ms.
this.clock.tick(500);
expect(a_function_should_be_runned.called).to.be.false;
// Advance clock again (1s since start)
this.clock.tick(500);
expect(a_function_should_be_runned.called).to.be.false;
// Advance clock again (1.5s since start). This should
// trigger the call to `a_function_should_be_runned`.
this.clock.tick(500);
expect(a_function_should_be_runned.called).to.be.true;
});
});
内容总结
以上是互联网集市为您收集整理的javascript – 如何为setInterval()函数编写测试用例全部内容,希望文章能够帮你解决javascript – 如何为setInterval()函数编写测试用例所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。