0

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()
    }

});
4

1 に答える 1

2

スパイはスパイしている関数を呼び出すため、スパイを使用できます。

var cb = sinon.spy(completed);

ただし、何らかの理由でイベント ハンドラーが呼び出されない場合、テストはタイムアウトして失敗します。

于 2016-08-10T14:46:54.933 に答える