【发布时间】: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