所以,我试着做一次摩卡测试,更准确地说,是查克拉姆测试。问题是,我从MongoDB中的一个集合中获取数据,我希望将这些数据存储在一个全局变量中,以运行一些测试。问题是,在回调内部,我得到了数据,但它没有设置运行测试的全局变量。
这是代码
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("virtus-app@virtus.ufcg.edu.br");
})
});我相信问题不在于Chakram,因为我还没有在这个代码中使用过。
发布于 2016-11-04 15:24:00
您的before函数是异步的。您应该使用不同的签名来告诉mocha,它必须等到测试完成后才能运行测试。
before("Getting user data", function(done) {
...
var test = function(email, token) {
gl_email = email;
gl_token = token;
done();
}
...
});只有在done()被调用之后,剩下的代码才会由mocha执行。
Mocha docs有一个关于如何测试异步代码https://mochajs.org/#asynchronous-code的非常全面的指南。
https://stackoverflow.com/questions/40426174
复制相似问题