【发布时间】:2018-03-28 17:33:06
【问题描述】:
我很难测试我的代码中的错误是否成功抛出正确的消息。发生的情况是错误正确抛出,但我的测试失败了。
模块:
// users.ts
const database = require('../databases/postgres');
module.exports = {
create: async (req, res, next) => {
try {
if (!req.body.email) {
throw new Error('email needed');
}
const userCreated = await database.createUser(user);
userCreated ? res.status(200).send('success') : res.status(409).send('user already exists');
} catch(err) {
next(err);
}
}
}
测试:
// users.test.ts
const expect = require('chai').expect;
const users = require('./users');
describe('create()', () => {
it('should send an error if the user does not have an email', (done) => {
const fakeReq = {
body: {
password: 'abc'
}
};
const fakeRes = {};
expect(() => {
users.create(fakeReq, fakeRes, done)
}).to.throw(Error, 'email needed')
});
});
我对这个问题感到慌乱,不确定它是我的测试、chai/typescript 不兼容还是我如何尝试使用 async/await?感谢您的帮助。
【问题讨论】:
-
但是你发现了你的错误。
-
我是,这不是正确的方法吗?或者我也应该将我的测试包装在一个 try/catch 块中?
-
expect(() => {这里一定是未缓存的错误}).to.throw。如果你在函数中抛出错误,你不能在同一个函数中处理它。在您的情况下,根本不能尝试/捕获。排除 db 驱动程序可能引发错误的情况。
-
谢谢!它成功了,我学到了更多关于错误处理的知识。如果有机会,您能否提交您的第二条评论作为答案?我会批准它作为我接受的答案:)
标签: typescript express chai