【问题标题】:Using chai to mock http requests使用 chai 模拟 http 请求
【发布时间】:2018-08-09 08:51:14
【问题描述】:

我正在测试一个使用 express 编写的 nodejs 应用程序。对于单元测试,我使用 chai 和 sinon。我的 API 中有以下要测试的路由。

在我的测试中,我正在使用以下代码模拟 get 请求:

 chai.request(app)
            .get('/downloads')
            .send({ wmauth: {
                    _identity: {
                        cn: "username",
                    }
                } })
            .end((err, res) => {
            res.status.should.be.equal(200);
            res.body.should.be.a('object');
            res.body.should.have.property('Items', []);

            AWS.restore('DynamoDB.DocumentClient');
            done();

但是,我总是收到错误消息“无法读取未定义的属性 '_identity'”。因为请求中没有发送对象“wmauth”,所以它是未定义的。我曾尝试使用 send 方法尝试将其包含在请求中,但没有运气。我想我需要以某种方式模拟它并将其发送到请求中,但不知道该怎么做。有人可以帮我解决这个问题吗? 下面要测试的方法:

 app.get('/downloads', async (req, res) => {
    const created_by_cn = req.wmauth['_identity'].cn;
    if(!created_by_cn) {
        return res.status(400).json({
            error: 'Mandatory parameters: created_by_cn',
        });
    }
    try {
        const data = await downloadService.getDownloads(created_by_cn);
        return res.status(200).json(data);
    }
    catch(error){
        res.status(500).json({error: error.message});
    }
});

谢谢

【问题讨论】:

    标签: javascript node.js unit-testing sinon chai


    【解决方案1】:

    我猜你忘了使用req.body,如:

    const created_by_cn = req.body.wmauth['_identity'].cn;
    

    希望能解决你的问题

    【讨论】:

      【解决方案2】:

      由于chai-http使用superagent,所以根据其doc,您需要使用query()才能在get请求中传递查询参数:

      chai.request(app)
                  .get('/downloads')
                  .query({ wmauth: {_identity: {cn: "username"}}})
                  .end((err, res) => { ... });
      

      然后在express路由中可以找到req.query中的参数:

      app.get('/downloads', function (req, res) {  
        const created_by_cn = req.query.wmauth._identity.cn;
        ...
      })
      

      【讨论】:

        猜你喜欢
        • 2012-12-11
        • 2016-11-19
        • 1970-01-01
        • 2017-10-05
        • 2018-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多