15

I'm getting started with mocha testing framework with NodeJS. Success assertions working fine but if the assertion fails, my test timeouts. For asserting I've tried Should and Expect. For example (async code)

  it('should create new user', function(done){
    userService.create(user).then(function(model){
      expect(model.id).to.be(1); //created user ID
      done();
    }, done)
  });

Here the if model id is not 1 then the test timesout instead of reporting failed assertion. I'm sure I'm doing something wrong. Appreciate your help. Thanks!

Raedwald
  • 46,613
  • 43
  • 151
  • 237
Amitava
  • 5,013
  • 9
  • 37
  • 50

3 Answers3

18

Shawn's answer works, but there is a simpler way.

If you return the Promise from your test, Mocha will handle everything for you:

it('should create new user', function() {
  return userService.create(user).then(function(model){
    expect(model.id).to.be(1); //created user ID
  });
});

No done callback needed!

danvk
  • 15,863
  • 5
  • 72
  • 116
17

expect is throwing an error that is being caught by the promise. Adding a catch condition that calls done fixes this.

it('should create new user', function(done) {
    userService.create(user).then(function(model) {
        expect(model.id).to.be(1); //created user ID
        done();
    }).catch(function(e) {
        done(e);
    })
});
Shawn
  • 186
  • 1
  • 3
  • If you're using mocha 1.18 or better, danvk's answer below is better. I almost missed seeing that answer myself, so I'm commenting here for visibility. – Retsam Dec 05 '15 at 19:10
0

Looks like done is never called. Besides then, you may also need an else to handle the failure.

Chen
  • 1,654
  • 2
  • 13
  • 21