2015-11-17 76 views
1

我想知道如果我關於sinon.js丟失了任何東西我嘗試過使用sinon.stub()。返回並返回結果,但無法獲得結果。任何指針將是有益的在node.js中使用sinon的摩卡存根

我有調用從DB

var users = require('/users'); 
module.exports.getProfileImage = function (req, res) { 
var profile = {}; 
    else { 
     users.findOne("email", req.session.user.email, function (err, user) { 
      if (err) { 
       res.status(400).send(); 
      } 
      else if (!user) { 

       //return default image 
      } 
      else if (user) { 
       //Do some other logic here 
      } 
     }); 

}; 

我使用摩卡作爲測試框架,也是用興農返回值的另一個模塊的模塊。我面臨的問題是當我創建一個users.findOne的存根以返回一個值時,控件不會來到我的else if(user)條件。

我的單元測試情況如下

describe("Return image of user",function(){ 

var validRequest = null; 
validRequest={ 
     session:{ 
      user:{ 
       email:'[email protected]', 
       role:'Hiring Company' 
      } 
     } 
    }; 
it("Should return an image from the file if the user is present in db",function(done){ 
var findOneUserResponse ={ 
     companyName:"xyz", 
     email:"[email protected]" 
    }; 
    var findOne = sinon.stub(mongoose.Model, "findOne"); 
    findOne.callsArgWith(1,null,findOneUserResponse); 

    user.getProfileImage(validRequest,response); 

    var actualImage = response._getData(); 
    findOne.restore(); 
    done(); 

}; 

}; 

回答

0

所以我通過sinon.js文檔http://sinonjs.org/docs/去了,整個就是我失蹤

describe("Return image of user",function(){ 

var validRequest = null; 
validRequest={ 
    session:{ 
     user:{ 
      email:'[email protected]', 
      role:'Hiring Company' 
     } 
    } 
}; 
it("Should return an image from the file if the user is present in db",function(done){ 
var findOneUserResponse ={ 
    companyName:"xyz", 
    email:"[email protected]" 
}; 
var findOne = sinon.stub(mongoose.Model, "findOne",function(err,callback){ 
    callback(null,findOneUserResponse); 
)}; 

user.getProfileImage(validRequest,response); 

var actualImage = response._getData(); 
findOne.restore(); 
done(); 
}; 
}; 
+0

你是怎麼丟失的?來了 – nbkhope

+1

我需要存根響應,而不是測試進入模塊的內容,所以在findOne var的回調函數中,我返回了我期望的響應 –