2015-01-20 42 views
5

想測試我的方法時,我得到了以下錯誤:節點快速測試的模擬res.status(狀態)以.json(OBJ)

TypeError: Cannot call method 'json' of undefined

下面是我的代碼,我會得到相同的錯誤'狀態',如果我從測試方法中刪除res.status。

如何定義「JSON」,所以我不得到一個異常拋出時:

res.status(404).json(error);

測試這個功能時。

stores.js

{ //the get function declared above (removed to ease of reading) 
     // using a queryBuilder 
     var query = Stores.find(); 
     query.sort('storeName'); 
     query.exec(function (err, results) { 
      if (err) 
       res.send(err); 
      if (_.isEmpty(results)) { 
       var error = { 
        message: "No Results", 
        errorKey: "XXX" 
       } 
       res.status(404).json(error); 
       return; 
      } 
      return res.json(results); 
     }); 
    } 

storesTest.js

it('should on get call of stores, return a error', function() { 

    var mockFind = { 
     sort: function(sortOrder) { 
      return this; 
     }, 
     exec: function (callback) { 
      callback('Error'); 
     } 
    }; 

    Stores.get.should.be.a["function"]; 

    // Set up variables 
    var req,res; 
    req = {query: function(){}}; 
    res = { 
     send: function(){}, 
     json: function(err){ 
      console.log("\n : " + err); 
     }, 
     status: function(responseStatus) { 
      assert.equal(responseStatus, 404); 
     } 
    }; 

    StoresModel.find = sinon.stub().returns(mockFind); 

    Stores.get(req,res); 

回答

10

的約定可鏈接的方法是總是在最後返回this。在你的測試中,你模擬了res對象。該對象上的每個方法應以return this;結尾。

res = { 
    send: function(){ }, 
    json: function(err){ 
     console.log("\n : " + err); 
    }, 
    status: function(responseStatus) { 
     assert.equal(responseStatus, 404); 
     // This next line makes it chainable 
     return this; 
    } 
} 
+1

'send'和'json'不是可鏈接的,所以如果你定義它,可能會導致誤報測試。 https://github.com/strongloop/express/blob/master/lib/response.js#L222 – Chris 2015-11-23 20:41:58

+0

我想你是對的 - 'status'方法是真正需要鏈接的唯一東西。我已經更新了我的答案。 – 2015-11-24 20:53:59

+0

我確實看到了有關返回這個的sinon documention。我們應該可以執行如下操作: status:sinon.stub()。returnThis() – 2018-02-08 22:12:16