【问题标题】:Node Express testing mock res.status(status).json(obj)Node Express 测试模拟 res.status(status).json(obj)
【发布时间】:2015-01-20 19:02:15
【问题描述】:

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

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

下面是我的代码,如果我从测试方法中删除 res.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);
        });
    }

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);

【问题讨论】:

    标签: node.js express mocha.js sinon


    【解决方案1】:

    status 方法恰好是 chainable method。可链接方法的约定是总是在最后返回this。在您的测试中,您模拟了res.status 方法,但忘记了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; 
        }
    }
    

    【讨论】:

    • sendjson 不可链接,因此如果您这样定义,可能会导致误报测试。 github.com/strongloop/express/blob/master/lib/response.js#L222
    • 我猜你是对的 - status 方法是唯一真正需要可链接的方法。我已经更新了我的答案。
    • 我确实看到 sinon 文档提到了返回这个。我们应该可以做类似 status: sinon.stub().returnThis()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-15
    • 2012-11-21
    • 2013-10-05
    • 2015-07-18
    • 2023-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多