2015-04-16 159 views
-2

我第一次玩摩卡,我很难得到一个简单的测试工作。调用在变量被赋值之前返回,因此返回为未定义。摩卡异步测试失败,未定义AssertError

这里是我想测试代码:

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" : "[email protected]"}).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(); 
    }); 
}) 

当我运行 '摩卡' 我收到以下:

#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

'helpers.emailAddressExists(returnVal);'。它必须在这里崩溃,因为'returnVal'没有分配任何值... –

+4

你的函数'emailAddressExists'没有做任何你想要的东西。你会想看看回调。 –

+0

@MadhavanKumar - 它不应该要求returnVal被初始化,它应该从emailAddressExists调用权中分配一个值? –

回答

1

首先,您将要更改emailAddressExists以进行回调 - 这是您测试时唯一可以告诉测试的方法完成:

var emailAddressExists = function (next) { 
    mongodb.connect(mongoURI, function (err, db) { 
    if (err) { 
     next(err); 
    } 

    var collection = db.collection(dbName); 
    collection.find({ "emailAddress" : "[email protected]"}).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),第二个参数为“返回值”。

+0

这工作。谢谢! –