简体   繁体   中英

Unit testing nodejs events

I'm using a solution explained in this answer to unit test events in my node application.

However, the setTimeout function never calls and so my tests pass when they should fail.

Here is an example:

suite('myTests', function() {
    test('myFunction_whenCalled_emitsEvent', function() {
        var myClass = new MyClass();
            var eventTimeout = setTimeout(function() {
                assert(false);
            }, 1000);
            myClass.on('something', function() {
                clearTimeout(eventTimeout);
            });
            myClass.doSomething(); // this does not emit the 'something' event
    });
});

I would expect this to fail, after 1 second as long as the 'something' event is not raised.

I put a breakpoint in the assert(false) line and it is never hit.

Could someone point me in the right direction ? Thanks.

You must use the done callback to show that your test is finished. Something like this:

suite('myTests', function() {
    test('myFunction_whenCalled_emitsEvent', function(done) {
        var myClass = new MyClass();
        myClass.on('something', function() {
            done();
        });
        myClass.doSomething();
    });
});

It looks like you are only testing whether the event is emitted. If this is the case, then the whole setTimeout thing is unnecessary. Mocha will itself timeout if it does not get done without the default timeout (2000ms, if I recall correctly).

The way your code was set, Mocha would just schedule your event and then exit the test. Since scheduling the event was successful, Mocha would call the test successful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM