Search code examples
node.jsjasmine-node

jasmine-node async doesn't understand code errors


I am trying jasmine-node with async :

it('should not be dumb', function(done){
Promise.resolve(0).then(function(){
  console.log('dumb');
  expect(2).toEqual(2);
  done();
});

});

returns :

dumb
.

Finished in 0.026 seconds
1 test, 1 assertion, 0 failures, 0 skipped

But somehow, if I have an error in my code:

  it('should not be dumb', function(done){
  Promise.resolve(0).then(function(result){
    console.log('dumb');
    expect(2,toEqual(2));
    done();
    }, function (err){console.log(err); done()});
  });

It just sits there until it times out, without any useful output:

dumb

Pairing user stories - 7816 ms
    should not be dumb - 7815 ms

Failures:

  1) Pairing user stories should not be dumb    Message:
     timeout: timed out after 5000 msec waiting for spec to complete    Stacktrace:
     undefined

Finished in 46.884 seconds 1 test, 1 assertion, 1 failure, 0 skipped

What am I doing wrong?


Solution

  • Assume this:

    promise.then(onResolve, onReject)
    

    onReject will be called when promise is rejected. However, in your code, the rejection happens in onResolve (implicitly, by an error being thrown), which doesn't affect promise (which has already been resolved at that point) and hence will not call onReject.

    If you want to catch errors being thrown in an onResolve, you need to handle them by adding another rejection handler to your promise chain:

    Promise.resolve(0).then(function(result){
      console.log('dumb');
      expect(2,toEqual(2));
      done();
    }).then(null, function (err) {
      console.log(err);
      done()
    });
    

    If Promise happens to be bluebird, you can shorten it somewhat by using .catch():

    Promise.resolve(0).then(function(result){
      console.log('dumb');
      expect(2,toEqual(2));
      done();
    }).catch(function (err) {
      console.log(err);
      done()
    });