2015-04-16 119 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

這工作。謝謝! –