【发布时间】:2015-01-15 16:58:21
【问题描述】:
环境:Mocha、Sinon、node.js。当其中有 5500 毫秒的超时时间时,为什么这个测试会在 8 毫秒内执行?也许我不明白什么是计时器?我的意思是,它应该暂停执行,对吗?直到计时器结束才完成测试。
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;
});
【问题讨论】:
-
sinon.useFakeTimers()将全局setTimeout函数替换为一个版本,该版本在假时钟超过计时器的超时值时同步(立即)运行其回调。这就是为什么测试运行得很快。这是一件好事,您不希望您的单元测试每次测试花费 5 秒。
标签: javascript timer timeout mocha.js sinon