gpt4 book ai didi

javascript - 如何为 setInterval() 函数编写测试用例

转载 作者:数据小太阳 更新时间:2023-10-29 06:15:41 24 4
gpt4 key购买 nike

我有一个计时器并假设当计数器计数到 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() 函数编写测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34309004/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com