繁体   English   中英

如何使用 Chai、Sinon、Mocha 在 Node.js 中测试控制器

[英]How to test a controller in Node.js using Chai, Sinon, Mocha

我一直在学习如何编写更好的单元测试。 我正在开发一个项目,其中控制器遵循如下所示的“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);
     });
   });
});

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

integration-test将应用程序威胁为黑匣子,其中网络是输入(HTTP 请求),而 3rd 方服务是应该模拟的依赖项(DB)。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM