我想使用 sinon 存根来异步测试事件发射器。我希望存根在调用后调用回调。
我以为stub.yields
是我想要的,但不是。有没有一种巧妙的方法来做到这一点?
it('asynchronously emits finish after logging is complete', function(done){
const EE = require('events');
const testEmitter = new EE();
var cb = sinon.stub();
cb.calls(completed); // no such method but this is what I need
testEmitter.on('finish', cb.bind(null));
testEmitter.emit('finish');
function completed() {
expect(cb).to.have.been.calledOnce;
expect(cb).to.have.been.calledOn(null);
expect(cb).to.have.exactArgs();
done()
}
});
目前,我正在做这样的事情......
it('asynchronously emits finish', function(done) {
const EE = require('events');
const testEmitter = new EE();
var count = 1;
process.nextTick(() => testEmitter.emit('finish'));
function cb(e) {
var self = this;
expect(e).to.be.an('undefined');
expect(self).to.equal(testEmitter);
if(!count--)
done()
}
testEmitter.on('finish', cb);
process.nextTick(() => testEmitter.emit('finish'));
});
它工作得很好,但是,我需要概括它,我认为我可以用 sinon 更有效地做到这一点。但我无法从 sinon docs 中弄清楚如何做到这一点。我错过了什么吗?
感谢罗伯特克莱普,这是解决方案......
it('asynchronously emits finish after logging is complete', function(done){
const EE = require('events');
const testEmitter = new EE();
var cb = sinon.spy(completed);
process.nextTick(() => testEmitter.emit('finish'));
testEmitter.on('finish', cb.bind(null));
process.nextTick(() => testEmitter.emit('finish'));
function completed() {
if(cb.callCount < 2)
return;
expect(cb).to.have.been.calledTwice;
expect(cb).to.have.been.calledOn(null);
expect(cb).to.have.been.calledWithExactly();
done()
}
});