我很难测试我的代码中的错误是否成功抛出了正确的消息。发生的事情是错误是正确抛出但是我的测试失败了。
模块:
// 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 /打字稿是不兼容的,还是我尝试使用async / await?我感谢任何帮助。
答案 0 :(得分:0)
Vayrex的评论让我走上了正确的道路。我从try / catch块中移出了抛出的错误,我也继续使用Chai的chai-as-promise模块。以下是为我制定的代码示例。
// users.ts
module.exports = {
create: async (req, res, next) => {
if (!userInput.email) {
throw new Error('email needed');
}
try {
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');
const chaiAsPromised = require("chai-as-promised");
require('chai').use(chaiAsPromised);
describe('create()', () => {
it('should send an error if the user does not have an email', (done) => {
const fakeReq = {
body: {
password: 'abc'
}
};
const fakeRes = {};
return expect(users.create(fakeReq, fakeRes)).to.be.rejectedWith(Error, 'email needed');
});
});