【问题标题】:How to correct the "connection.readyState" of mongoose on test cases from "connecting" to "connected"?如何更正测试用例中猫鼬的“connection.readyState”从“正在连接”到“已连接”?
【发布时间】:2013-04-15 10:07:27
【问题描述】:

我在猫鼬中创建了一个用户(注册)模型。该模型可以从 mocha 中创建的测试用例以及前端的注册表单中访问。新用户可以通过前端从注册表中保存,但是用mocha编写的测试用例不能保存。

当我检查代码时,猫鼬的 connection.readyState 在测试用例中是 2(connecting),在用户注册表中是 1(connected)。

models/users.js

var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/test');

console.log('conn ready:  '+mongoose.connection.readyState);
// "conn ready: 2"  i.e connecting for test case as well as from user register form 

var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId,
    UserSchema = new Schema({
       // schemas
    });

UserSchema.statics.newUser = function (uname, email, pass) {
    var instance = new User();
    instance.uname  = uname;
    instance.email  = email;
    instance.pass   = pass;
    console.log("conn state: "+mongoose.connection.readyState); 
    // "conn state: 2"  i.e connecting for test case. But  1  i.e connected for  user register form 

    instance.save(function (err) {
      // Do rest
    });
};

var User = mongoose.model('User', UserSchema);

exports.User = User;

如何纠正测试用例上mongoose的connection.readyState

【问题讨论】:

    标签: javascript node.js express mongoose mocha.js


    【解决方案1】:

    问题在于mocha测试文件中it方法的参数传递。我忘记将it 方法的done 参数放在测试用例中,并且没有在测试用例末尾调用传递的函数done()

    describe('User', function () {
        it('new user create', function (done) {
                                        ^^^^   
            User.newUser(
                'test','test@test.com', 'test123',
                function (err, user) {
                    should.not.exist(err);
                    done();
                    ^^^^^^
                }
            );
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2014-02-05
      • 2021-07-15
      • 1970-01-01
      • 1970-01-01
      • 2020-11-08
      • 2012-02-07
      • 2018-08-03
      • 2016-04-13
      • 1970-01-01
      相关资源
      最近更新 更多