【问题标题】:How do i test for http status code 500 in sinon?如何在 sinon 中测试 http 状态码 500?
【发布时间】:2018-11-14 08:33:00
【问题描述】:

我在 nodejs 的主类中有以下代码。

我正在使用 sinon 进行单元测试。

如何测试这部分代码 res.status(error.status || 500);

我可以通过调用导致上述错误处理 404 的无效 url 来测试 error.status 部分,但我如何进入500 流?

ma​​in.js:

...
//importing route
var routes = require('./api/rest/webservRest'); 

//register the route
routes(app); 

//reached here throw error 404, means no routes to handle inc. request
app.use((req, res, next) => {
    const error = new Error('Not found');
    error.status = 404;

    next(error);
});

// catch errors
app.use((error, req, res, next) => {

    log.error("ERROR - " + req.url + " - " + error.message);

    res.status(error.status || 500);
    res.json({
        error: {
            message: error.message
        }
    }); 
});

//start application
module.exports = app.listen(port, () => {
    log.info('Module - RESTful API server started on: ' + port);    
});

【问题讨论】:

    标签: node.js unit-testing sinon


    【解决方案1】:

    如果error.status 返回虚假值,例如falseundefined,则500 将被捕获。

    所以也许你可以使用 Sinon 对error 进行存根,如下所示:

    const error = {
      status: false,
      message: 'something'
    }
    

    const error = {
      message: 'something'
    }
    

    希望对你有帮助

    【讨论】:

    • 我还是不明白。这是否意味着我需要存根app.use((error, req, res, next)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 2011-01-01
    • 2014-01-08
    • 1970-01-01
    • 2012-12-04
    • 2017-11-01
    相关资源
    最近更新 更多