Node Express测试模拟res.status(状态).json(obj)

myg*_*221 11 mocha.js node.js express sinon

尝试测试我的方法时出现以下错误:

TypeError:无法调用未定义的方法'json'

下面是我的代码,如果我从测试方法中删除res.status,我会得到"status"的相同错误.

我如何定义'json'所以我没有得到一个异常抛出:

res.status(404)上传.json(误差);

在测试此功能时.

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);
        });
    }
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

Rya*_*ale 17

可链接方法的约定总是status在最后返回.在测试中,您模拟了this对象.该对象上的每个方法都应该以res.status.

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; 
    }
}
Run Code Online (Sandbox Code Playgroud)