user3414982
user3414982

Reputation: 387

Error: timeout of 2000ms exceeded. Unit test with promises

My unit tests make http requests to NET API and use kriskowal q library. When I do assert call in then callback and assertion fails I see Error: timeout of 2000ms exceeded instead of AssertionError. I wrote example to illustrate this situation:

var assert = require('assert')
  , Q = require('q');

it('promise', function(cb){
    var deferred = Q.defer();
    deferred.promise.then(function(){
        assert(false);
        cb();
    });
    deferred.resolve();
});

I can't understand this behaviour. Modelling asynchronous behaviour with setTimeout/setImmediate shows normal AssertionError.

Upvotes: 1

Views: 3845

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276286

Q does not provide unhandled rejection tracking, you need to explicitly .done promises to signal a chain has ended. You get a suppressed error in your test:

it('promise', function(cb){
    var deferred = Q.defer();
    deferred.promise.then(function(){
        assert(false);
        cb();
    }).done(); // NOTE THE DONE
    deferred.resolve();
});

Mocha however, provides better promise syntax, you can simply return a promise and have the rejection turn to a test failure:

it('promise', function(cb){
    return new Q.Promise(function(resolve){ resolve(); }). // use the new syntax
    then(function(){
        assert(false);
        cb();
    });// no done needed because of the `return`
});

Upvotes: 2

Related Questions