javascript - 我正在尝试使用 mocha 和 chai 测试 API 返回 500(内部服务器错误)的条件
问题描述
拜托,我不知道如何去做。对该过程的良好解释将有很大帮助。感谢期待。
这是我的控制器
async getAllEntries(req, res) {
try {
const userId = req.userData.userID;
const query = await client.query(
`SELECT * FROM entries WHERE user_id=($1) ORDER BY entry_id ASC;`, [
userId,
],
);
const entries = query.rows;
const count = entries.length;
if (count === 0) {
return res.status(200).json({
message: 'There\'s no entry to display',
});
}
return res.status(200).json({
message: "List of all entries",
"Number of entries added": count,
entries,
});
} catch (error) {
return res.status(500).json({
message: "Error processing request",
error,
});
}
}
解决方案
对于这种情况,我要做的是使该client.query
过程失败。所以,根据你的代码,它会去catch
声明。
const chai = require('chai');
const assert = chai.assert;
const sinon = require('sinon');
const client = require('...'); // path to your client library
const controller = require('...'); // path to your controller file
describe('controller test', function() {
let req;
let res;
// error object to be used in rejection of `client.query`
const error = new Error('something weird');
beforeEach(function() {
req = sinon.spy();
// we need to use `stub` for status because it has chain method subsequently
// and for `json` we just need to spy it
res = {
status: sinon.stub().returnsThis(),
json: sinon.spy()
};
// here we reject the query with specified error
sinon.stub(client, 'query').rejects(error);
});
afterEach(function() {
sinon.restore();
})
it('catches error', async function() {
await controller.getAllEntries(req, res);
// checking if `res` is called properly
assert(res.status.calledWith(500));
assert(res.json.calledWith({
message: 'Error processing request',
error
}));
});
});
希望能帮助到你。
推荐阅读
- c# - 在 WPF 中,如何在 LostFocus 上进行绑定但在 PropertyChanged 上进行验证?
- javascript - 为什么我的下拉菜单只显示了一半?
- android - 如何使用 Flutter 使 Android 中的状态栏变暗?
- c - 为什么从用户信息输入时我必须在使用 fgets 之前使用 getchar
- python - 将 Python 数组转换为列表中的字符串 [Pandas]
- django - 如何知道您是否将两个套接字连接到 django 通道中的同一组通道层
- javascript - 打字稿中的嵌套数组过滤器()函数-总是返回true?
- azure - Azure 媒体服务许可证密钥成本/计数
- r - 如何为已经用 R 编码的 BA、MA、PhD 的人添加分类变量、大学
- html - 尝试使用 jQuery 创建汉堡菜单