所以,我試圖運行一個Mocha測試,更準確地說是一個Chakram測試。 問題是,我從MongoDB中的集合中獲取數據,並且我想將這些數據存儲在全局變量中以運行一些測試。 問題是,在回調中我得到的數據,但它沒有設置全局變量來運行測試。將MongoDb結果存儲到變量中以運行Mocha測試,但未定義
下面是代碼
var chakram = require('chakram'),
expect = chakram.expect;
describe("Test", function() {
var gl_email;
var gl_token;
before("Getting user data", function() {
var setAccessData = function() {
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost/virtusapp', function(err, db) {
if (err) throw err;
console.log("Connected to Database");
var user = db.collection('users').findOne({
name: "virtus-app"
});
user.then(function(result) {
email = result.email;
token = result.token1 + result.token2;
db.close(test(email, token))
});
});
}
var test = function(email, token) {
gl_email = email;
gl_token = token;
//Here the email and token are set, but it doesnt set the global variables
}
setAccessData();
});
it("should have set global email variable", function() {
//here gl_email should be set, but I get UNDEFINED.
expect(gl_email).to.eql("[email protected]");
})
});
我認爲,問題不在於環刃,因爲我還沒有在此代碼中使用呢。
是啊......問題更關係到變量範圍和異步執行,也許.... – Hackerman