What's the best way to unit test an event being emitted in Nodejs?

后端 未结 7 650
孤独总比滥情好
孤独总比滥情好 2021-02-05 02:12

I\'m writing a bunch of mocha tests and I\'d like to test that particular events are emitted. Currently, I\'m doing this:

  it(\'should emit an some_event\', fun         


        
相关标签:
7条回答
  • 2021-02-05 02:48

    Late to the party here, but I was facing exactly this problem and came up with another solution. Bret's accepted answer is a good one, but I found that it wreaked havoc when running my full mocha test suite, throwing the error done() called multiple times, which I ultimately gave up trying to troubleshoot. Meryl's answer set me on the path to my own solution, which also uses sinon, but does not require the use of a timeout. By simply stubbing the emit() method, you can test that it is called and verify its arguments. This assumes that your object inherits from Node's EventEmitter class. The name of the emit method may be different in your case.

    var sinon = require('sinon');
    
    // ...
    
    describe("#someMethod", function(){
        it("should emit `some_event`", function(done){
            var myObj = new MyObj({/* some params */})
    
            // This assumes your object inherits from Node's EventEmitter
            // The name of your `emit` method may be different, eg `trigger`  
            var eventStub = sinon.stub(myObj, 'emit')
    
            myObj.someMethod();
            eventStub.calledWith("some_event").should.eql(true);
            eventStub.restore();
            done();
        })
    })
    
    0 讨论(0)
提交回复
热议问题