2

I'm using Mongoose with promises by wrapping it this way with bluebird's method:

var mongoose = promise.promisifyAll(require('mongoose'))

Then I'm trying to use an async method:

var newUser = new User({email: 'd@a.com', password: '123', userType: 'admin', name: 'paco'});
newUser.saveAsync()
  .then(function (createdUser) {
    console.log(createdUser);
    should.exist(createdUser);
    done();
  })
  .catch(function (err) {
    console.log(err);
    should.not.exist(err);
    done();
  });

However, as the schema got an unique index for email field, if I try to run this multiple times an Unhandled rejection AssertionError: expected Error will be thrown causing it all to fail.

How can I properly handle any error?

diegoaguilar
  • 8,179
  • 14
  • 80
  • 129
  • `should.not.exist(err);` will throw an `AssertionError` when there is an `err`, which causes your test to fail. – Bergi Nov 24 '15 at 22:51
  • @Bergi how should I *handle it*? I only wait it to assume test failed, not to break it – diegoaguilar Nov 24 '15 at 22:52
  • So `.catch(done)` semantically means an non error test? – diegoaguilar Nov 24 '15 at 22:59
  • What is `done`, some testing framework callback? `.catch(done)` will cause the `done` handler to be called with any exceptions as the first argument, which will typically cause the respective test to fail. It will prevent the unhandled rejection. – Bergi Nov 24 '15 at 23:02
  • `done` is mocha's `it` blocks callback – diegoaguilar Nov 24 '15 at 23:02
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/96088/discussion-between-diegoaguilar-and-bergi). – diegoaguilar Nov 24 '15 at 23:09

1 Answers1

0

First of all, if you try to insert the same data in each test you will only have the first test run working so you must clear the database or delete this specific record before each test runs.

beforeEach(function() {
    return Model.findOneAndRemove({email: 'd@a.com'})
});

Mocha has now support for promises so there is no need for the done callback. Your test can be rewritten as:

var newUser = new User({
     email: 'd@a.com', 
     password: '123',
     userType: 'admin', 
     name: 'paco'
});
return newUser.saveAsync().should.eventually.be.fulfilled();
// or return newUser.saveAsync().should.eventually.be.equal(value);
devconcept
  • 3,665
  • 1
  • 26
  • 40