以下测试在与诗乃的假计时器和 Bluebird 一起使用时会卡住。
var sinon = require('sinon');
var Promise = require('bluebird');
describe('failing test', function() {
beforeEach(function() {
this.clock = sinon.useFakeTimers();
});
afterEach(function() {
this.clock.restore();
});
it('test', function(done) {
Promise.delay(1000).then(function(){
done(); //This never gets called
});
});
});
我正在将 Mocha (v2.2.5) 与 Bluebird (v2.9.33) 和 Sinon (v1.15.3) 一起使用。
我尝试了 Bluebird 和 Sinon 的一些讨论中提供的建议,但我无法成功。这似乎是 Sinon stub setImmediate 方式的问题,但除此之外我不知道如何解决这个问题。
最佳答案
您需要像这样手动步进假计时器:
describe('failing test', function() {
it('test', function(done) {
Promise.delay(1000).then(function(){
done(); //This never gets called
});
//
// ADVANCE THE CLOCK:
//
this.clock.tick(1000);
});
});
顺便说一句,mocha 内置了对 Promise 的支持,因此更好的方法是 return
你的 Promise:
describe('failing test', function() {
it('test', function() { // No more "done" callback
var p = Promise.delay(1000).then(function(){
console.log('done');
});
this.clock.tick(1000);
return p; // Return the promise instead - mocha will take of the async magic goodness!
});
});
根据我的经验,混合 Promise 和 done
回调样式会导致各种麻烦并且难以跟踪错误。使用 Promise 时,尽量坚持返回,并查看诸如 chai-as-promised 之类的库。 .我向你保证,它会让你的测试更具可读性!
关于node.js - Bluebird promise 在使用诗乃的假计时器时卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31403818/