1

I'm testing my NodeJS application with mocha and should. While the first test runs smoothly the second fails (error equals null). In both tests if got a valid user within the callback (both have the same id in mongoose). The tests obviously don't wait for the database action to take happen.

describe("User", function(){
    before(function (done) {
        // clear database
        model.UserModel.collection.remove(done);
    })

    it("should save", function(done){
        user1.save(function(error, user){
            should.not.exist(error);
            user.should.have.property("first_name", "Rainer");
            done();
        })
    })

    it("should not save duplicate user", function(done){
        user1.save(function(error, user){
            should.exist(error);
            done();
        })
    })
})


It also doesn't work when I place the second test in the callback of the first test. I want to test for a duplicate key error, but can't achieve it with the given situation.

robertklep
  • 198,204
  • 35
  • 394
  • 381
user1772306
  • 449
  • 1
  • 7
  • 20

1 Answers1

1

Looks like you're re-using the user1 document.

In Mongoose, you're allowed to save the same document again (for instance, after having made changes to it); it won't mean that a new document is saved, just that the old one will be updated.

If you want to test properly, you should create a new document instance (with the same properties as the first) in your second test.

robertklep
  • 198,204
  • 35
  • 394
  • 381