【发布时间】:2021-01-01 21:10:41
【问题描述】:
我一直在学习如何编写更好的单元测试。我正在开发一个项目,其中控制器遵循如下所示的“MyController”样式。基本上是一个“异步”函数,它“等待”许多外部调用并返回带有结果的状态。我为内部函数“dbResults”编写了一个非常基本的测试。但是,我不确定如何测试整个控制器函数本身是否返回某个值。在下面的例子中。我想知道是否有人可以帮助我找出测试“getUserWithId”等函数最终结果的正确方法。下面写的代码非常接近,但不完全是我实现的。任何建议将不胜感激。
控制器
export const MyController = {
async getUserWithId(req, res) {
let dbResults = await db.getOneUser(req.query.id);
return res.status(200).json({ status: 'OK', data: dbResults });
}
}
当前测试
describe ('MyController Test', () => {
describe ('getUserWithId should return 200', () => {
before(() => {
// create DB stub
});
after(() => {
// restore DB stub
});
it('should return status 200', async () => {
req = // req stub
res = // res stub
const result = await MyController.getUserWithId(req, res);
expect(res.status).to.equal(200);
});
});
});
【问题讨论】:
-
等等。你的控制器不会抛出错误
cannot call function status of undefined,因为res没有在任何地方定义吗? -
你是对的。我只是提供伪代码。我正在添加它。
-
如果你只是想测试你的控制器函数而不实际调用
getUserWithId,你可以模拟getUserWithId函数。如果你想检查 e2e 实现,我建议通过移动到它自己的 DAL 层来为 getUserWithId 函数创建单独的单元测试
标签: node.js mocha.js chai sinon