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 を使用するとより効率的に実行できると考えました。しかし、シノンのドキュメントからそれを行う方法がわかりません。何か不足していますか?
Robert Klepのおかげで、ここに解決策があります...
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()
}
});