2014-01-16 24 views
0

當我試圖運行摩卡測試時,我得到「無法確定服務器的狀態」 因爲貓鼬連接處於連接狀態。如何修正摩卡咖啡中的「connection.readyState」從「連接」改爲「連接?

請建議如何處理這種情況。

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; 

回答

4

DB連接調用connect它可能會報告說,它仍然連接後直接異步發生,所以當你檢查一下就可以了。如果你想連接後做一些事情,你需要一個回調

mongoose.connect('mongodb://localhost/test', function (error) { 
    // Do things once connected 
}); 

至於如何處理它在您的方案通過,我的建議是分離從模型連接,並連接到MongoDB的需要

因此,如果你在摩卡測試你的用戶模型,這可能是在Before

var mongoose = require("mongoose"); 

// Load in your user model wherever that is 
var User = require("../models/user"); 

describe("My user model tests", function() { 
    // Connect to mongodb here before you start testing 
    before(function (done) { 
    mongoose.connect('mongodb://localhost/test', function (error) { 
     if (error) throw error; // Handle failed connection 
     console.log('conn ready: '+mongoose.connection.readyState); 
     done(); 
    }); 
    }); 

    // And include disconnect afterwards 
    after(function (done) { 
    mongoose.disconnect(done); 
    }); 

    // Test your user model down here 
    it("passes some tests"); 
}); 

取決於你如何組織你的應用程序做,我建議你移動數據庫連接到一個合理的位置(例如服務器配置配給)。當你測試你的整個應用程序時(例如集成測試),你會在Before掛鉤中啓動你的服務器

0

另外,如果你在另一個文件(如我)中有貓鼬連接例程,你應該稍微等待readyState'連接'(1)。我在'之前'解決了它:

var app = require('../server'); //I have mongoose connection in this file 
var mongoose = require('mongoose'); 

var context = describe; 

describe('Initial DB routines', function() { 

    before(function (done) { 
    mongoose.connection.on('connected', done); 
    }); 

    it('Should connect to MongoDB', function(done) { 
    mongoose.connection.readyState === 1 ? done(): done(false); 
    }); 
}); 
相關問題