【问题标题】:How to test a controller in Node.js using Chai, Sinon, Mocha如何使用 Chai、Sinon、Mocha 在 Node.js 中测试控制器
【发布时间】: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


【解决方案1】:

我建议使用 integration-test 而不是 unit-test 来测试您的控制器。

integration-test 威胁应用程序作为一个黑盒子,其中网络是输入(HTTP 请求)和第 3 方服务作为应该被模拟的依赖项 (DB)。

  • unit-test 用于服务、工厂和实用程序。
  • integration-test 用于HTTP 和WebSockets 等外部接口

您也可以添加e2e-test,但如果您的设置中只有一个组件,您integration-test 就足够了。

【讨论】:

    猜你喜欢
    • 2018-11-05
    • 2018-05-05
    • 2017-10-08
    • 2021-09-27
    • 2015-12-01
    • 2018-04-08
    • 2017-10-23
    • 2016-09-22
    • 1970-01-01
    相关资源
    最近更新 更多