使用Mocha和should.js进行NodeJStesting数据库

我用摩卡testing我的NodeJS应用程序,应该。 第一次testing顺利进行时,第二次失败(错误等于空)。 在这两个testing中,如果在callback中有一个有效的用户(两者在mongoose中都有相同的ID)。 testing显然不等待数据库操作发生。

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(); }) }) }) 

当我在第一个testing的callback中放置第二个testing时,它也不起作用。 我想testing一个重复的键错误,但不能达到给定的情况。

看起来你正在重新使用user1文档。

在Mongoose中,您可以再次保存同一个文档(例如,在对其进行更改后)。 这并不意味着保存了新的文件,只是旧的文件会被更新。

如果你想正确testing,你应该在第二个testing中创build一个新的文档实例(与第一个属性相同)。