【问题标题】:TypeError mocking express response objectTypeError 模拟快速响应对象
【发布时间】:2016-12-11 04:00:40
【问题描述】:

我目前正在尝试使用sinonsinon-express-mock 编写测试来模拟不正确的请求,然后在我的应用程序中调用验证函数,以确保验证函数返回正确的响应状态(400)。但是,目前我收到错误TypeError: Cannot read property 'send' of undefined。我认为send 会与res 对象的其余部分一起被嘲笑,但如果不是,我怎么能做到这一点?提前致谢。

我正在测试的功能:

export const validateItemRequest = (req, res) => {
    if (!req.query.number) {
        return res.status(400).send('Number not specified');
    } else if ( req.query.number % 1 !== 0) {
        return res.status(400).send('Incorrect number syntax');
    } 
};

测试代码:

describe('item', function() {

    it('should only accept valid requests', function() {

        const itemRequest = {
            query: {
                number: 'abcde',
            },
        };

        const req = mockReq(request);
        const res = mockRes();

        itemController.validateItemRequest(req, res);

    });
});

【问题讨论】:

  • req.query.number % 1,什么时候模数不是0?
  • @Bindrid 当数字有小数位时

标签: javascript unit-testing express response sinon


【解决方案1】:

sinon-express-mock 目前不支持链接。有 an open issue to add chaining support,但这些方法目前不返回对象,因此无法从 res.status 链接到 send

我的测试只需要几个响应方法,所以我制作了自己的响应间谍,如下所示:

var response = {  
  status: sinon.spy(function() { return response; }),  
  send: sinon.spy(),  
  sendStatus: sinon.spy(),
  reset: function() {
    for (var method in this) {
      if (method !== 'reset') {
        this[method].reset();
      }
    }
  }
};

请注意,我只返回来自 status 的响应,因为您不应该链接 sendsendStatus

【讨论】:

    【解决方案2】:
    response = { 
       json:(obj) => { response.body = obj },
       status:function(status) {
         response.statusValue = status;
       return this;
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      • 1970-01-01
      • 1970-01-01
      • 2018-05-02
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多