我正在使用mocha测试我的NodeJS应用程序。当第一个测试平稳运行时,第二个测试失败(错误等于null)。在两个测试中,如果在回调中获得了有效用户(两者在mongoose中具有相同的id)。测试显然不等待数据库操作发生。
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();
})
})
})
当我将第二个测试放在第一个测试的回调中时,它也不起作用。
我想测试一个重复的键错误,但在给定的情况下无法实现它。
答案 0 :(得分:1)
您似乎正在重复使用user1
文档。
在Mongoose中,您可以再次保存同一文档(例如,在对其进行更改后);这并不意味着保存新文档,只是旧文档将被更新。
如果要正确测试,则应在第二次测试中创建一个新的文档实例(具有与第一个相同的属性)。