我第一次玩摩卡,我很难让一个简单的测试工作。调用在赋值变量之前返回,因此返回为undefined。
以下是我要测试的代码:
var mongodb = require('mongodb')
var querystring = require("querystring");
var mongoURI = process.env.MONGOLAB_URI;
var dbName = process.env.dbName;
//checks for a single email address
var emailAddressExists = function () {
var returnVal;
mongodb.connect(mongoURI, function (err, db) {
if (err)
{ console.error(err); response.send("Error " + err); }
var collection = db.collection(dbName); //, function(err, collection) {
collection.find( { "emailAddress" : "myemail@email.com"} ).count( function (err, count) {
if (count == 0) {
returnVal = false;
console.log("not Matched " + returnVal);
} else {
returnVal = true;
console.log("matched " + returnVal);
}
return returnVal;
});
});
)
exports.emailAddressExists = emailAddressExists;
我的测试是:
var assert = require('assert'),
helpers = require ('../lib/helpers.js');
describe('#emailAddressExistsTest()', function() {
var returnVal;
it('should return 1 when the value is not present', function(done) {
assert.equal(true, helpers.emailAddressExists(););
done();
});
})
当我运行'mocha'时,我会收到以下内容:
#emailAddressExistsTest()
1) should return 1 when the value is not present
0 passing (10ms)
1 failing
1) #emailAddressExistsTest() should return 1 when the value is not present:
AssertionError: true == "undefined"
at Context.<anonymous> (test/emailAddressCheck.js:25:11)
答案 0 :(得分:1)
首先,您将要更改emailAddressExists
以进行回调 - 这是在您完成时告诉测试的唯一方法:
var emailAddressExists = function (next) {
mongodb.connect(mongoURI, function (err, db) {
if (err) {
next(err);
}
var collection = db.collection(dbName);
collection.find( { "emailAddress" : "myemail@email.com"} ).count( function (err, count) {
if (count == 0) {
next(null, false);
} else {
next(null, true);
}
return returnVal;
});
});
)
然后,您必须向其传递一个回调并在回调中调用done
:
describe('#emailAddressExistsTest()', function() {
it('should return 1 when the value is not present', function(done) {
helpers.emailAddressExists(function(err, returnVal) {
// Maybe do something about `err`?
assert.equal(true, returnVal);
done();
});
});
})
你会发现这与我们在聊天中谈到的有点不同。 node.js
中的约定是回调的第一个参数是错误(如果没有错误则为null
),第二个参数是“返回值”。