admin管理员组文章数量:1287163
Consider the below function,
function helloAfter100ms(){
setTimeout(function(){
console.log('hello');
},100)
}
Test code with mocha,
describe('#helloAfter100ms()',function(){
it('console logs hello ONLY after 100ms',function(){
// what should go here
})
})
Consider the below function,
function helloAfter100ms(){
setTimeout(function(){
console.log('hello');
},100)
}
Test code with mocha,
describe('#helloAfter100ms()',function(){
it('console logs hello ONLY after 100ms',function(){
// what should go here
})
})
Share
Improve this question
asked Oct 15, 2017 at 11:34
kalpakalpa
6973 gold badges11 silver badges23 bronze badges
1
-
I suggest you to use also
sinon
with mocha, which offers you ways for spying/mocking stuff and times manipulation for these cases oftimeout
for example: github./mochajs/mocha/wiki/Spies – quirimmo Commented Oct 15, 2017 at 11:42
2 Answers
Reset to default 11I think you're trying to test something that you shouldn't. The name of your test suggests you don't trust that the setTimeout
function calls the console.log
only after the given timeout.
Since this is not your code, you should probably not unit test it. Furthermore, setTimeout
is probable something you can be sure works properly.
So what's left to test? Your code - the code that calls setTimeout
.
You can make sure that you're calling setTimeout correctly.
As to how this is done - there are two sinon features you can use. The first is useFakeTimers
which gives you control of the clock. The second is a spy, which you should use on the console.log
to make sure it was called.
describe('#helloAfter100ms()',function(){
it('console logs hello ONLY after 100ms',function(){
const clock = sinon.useFakeTimers();
const logSpy = sinon.spy(console, 'log');
helloAfter100ms();
expect(logSpy).to.not.have.been.called;
clock.tick(100);
expect(logSpy).to.have.been.calledOnce;
logSpy.restore();
clock.restore();
}
}
Updated: like this:
describe('helloAfter100ms', function(){
it('console logs hello ONLY after 100ms', function(done){
setTimeout(function(){
console.log('hello.');
done();
}, 100)
})
})
Reference: https://mochajs/#asynchronous-code
本文标签: javascriptHow to test a function that uses setTimeout() internally with mochaStack Overflow
版权声明:本文标题:javascript - How to test a function that uses setTimeout() internally with mocha? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741278201a2369854.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论