简体   繁体   English

使用Mocha和should.js的NodeJS测试数据库

[英]NodeJS testing Database with Mocha and should.js

I'm testing my NodeJS application with mocha and should. 我正在用mocha测试我的NodeJS应用程序,并且应该。 While the first test runs smoothly the second fails (error equals null). 当第一个测试运行顺利时,第二个失败(错误等于null)。 In both tests if got a valid user within the callback (both have the same id in mongoose). 在这两个测试中,回调中是否都有有效的用户(猫鼬中的ID均相同)。 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. 我想测试重复的键错误,但是在给定的情况下无法实现。

Looks like you're re-using the user1 document. 看起来您正在重新使用user1文档。

In Mongoose, you're allowed to save the same document again (for instance, after having made changes to it); 在Mongoose中,允许您再次保存同一文档(例如,对其进行更改后); 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. 如果要正确测试,则应在第二个测试中创建一个新的文档实例(具有与第一个实例相同的属性)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM