Node Expresstesting模拟res.status(状态).json(obj)
尝试testing我的方法时出现以下错误:
TypeError:不能调用未定义的方法'json'
下面是我的代码,如果我从testing方法中删除res.status,我会得到'状态'相同的错误。
我如何定义'JSON',所以我没有得到一个exception抛出:
res.status(404)上传.json(误差);
当testing这个function。
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);
可链式方法的惯例是总是在最后返回this
。 在你的testing中,你模拟了res
对象。 该对象上的每个方法应该以return this;
结束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; } }