Env: Mocha, Sinon, node.js.为什么这个测试在 8 毫秒内执行,而其中有 5500 毫秒的超时?也许我不明白计时器是什么?我的意思是,它应该闲置执行,对吗?在计时器出来之前不要完成测试。
var sinon = require('sinon');
var chai = require('chai');
expect = chai.expect;
should = chai.should();
assert = chai.assert;
var clock;
beforeEach(function () {
clock = sinon.useFakeTimers();
});
afterEach(function () {
clock.restore();
});
it("should time out after 5000 ms", function() {
var timedOut = false;
setTimeout(function () {
timedOut = true;
}, 5000);
timedOut.should.be.false;
clock.tick(5500);
timedOut.should.be.true;
});
我找到了在 mocha 中为 node.js 制作 setTimeOut 的方法。
// We need to pass the mocha's function 'done' that tells mocha to wait till this function is called
it('It should wait around 5 seconds', function(done){
// We augment mocha's timeout to more than default 2000ms
// we put more than the 5 seconds of setTimeout to asure us
this.timeout(6 * 1000);
setTimeout(function(){
// tells mocha we are finished
done();
}, 5*1000);
});
这是茉莉花中"等待"功能的替代品。