【发布时间】:2021-10-03 13:43:42
【问题描述】:
所以我是测试新手,并且已经设置了这个模拟数据库调用失败的方法的基本测试(对不起,如果我的术语不太正确)
我用的是sequelize,所以Job是模型,findAndCountAll是相关方法。
it('Should throw a 500 error if accessing the DB fails', () => {
sinon.stub(Job, 'findAndCountAll');
Job.findAndCountAll.throws();
const req = {
query: {
index: 0,
limit: 10,
orderField: 'createdAt',
order: 'DESC'
}
};
adminController.getJobs(req, {}, () => {}).then(result => {
expect(result).to.be.an('error');
expect(result).to.have.property('statusCode', 500);
done();
})
Job.findAndCountAll.restore();
})
我的问题是我的大部分代码都是使用承诺链编写的:
exports.getJobs = (req, res, next) => {
const index = req.query.index || 0;
const limit = req.query.limit || 10;
const orderField = req.query.orderField || 'createdAt';
const order = req.query.orderDirection || 'DESC';
Job.findAndCountAll({
// ...arguments
})
.then(results => {
res.status(200).json({ jobs: results.rows, total: results.count });
return // Attempted to add a return statement to enter the .then() block in the test
})
.catch(err => {
if(!err.statusCode) err.statusCode = 500;
next(err);
return err; // Attempted to return the error to enter the .then() block in the test
});
这不起作用,我的(不必要的)返回语句也无济于事。
但是,使用async await 重写方法确实有效(见下文)。但是我想避免重写我的所有代码,如果能理解这里的区别会很好。
我最好的猜测是,与其让 sinon 存根抛出错误,不如让它拒绝承诺?我只是不完全确定这是否正确,或者如何实现。我有点在不知道的文档中磕磕绊绊
任何帮助表示赞赏,
谢谢,
尼克
exports.getJobs = async(req, res, next) => {
const index = req.query.index || 0;
const limit = req.query.limit || 10;
const orderField = req.query.orderField || 'createdAt';
const order = req.query.orderDirection || 'DESC';
try {
const results = await Job.findAndCountAll({ //...params });
// ...
res.status(200).json({ jobs: results.rows, total: results.count });
return;
} catch(err) {
if(!err.statusCode) err.statusCode = 500;
next(err);
return err;
}
};
【问题讨论】:
-
您的
getJobs函数根本没有return语句。你需要让它返回承诺链Job.findAndCountAll({…}).then(…).catch(…)。 -
谢谢@Bergi,是的,我最终发现了那个(在下面的答案中)。我确实犯了很多错误,但学到了很多!
标签: javascript unit-testing mocha.js sinon