简体   繁体   English

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

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

I've been learning how to write better unit tests.我一直在学习如何编写更好的单元测试。 I am working on a project where controllers follow the style of 'MyController' shown below.我正在开发一个项目,其中控制器遵循如下所示的“MyController”样式。 Basically an 'async' function that 'awaits' on many external calls and returns a status with the results.基本上是一个“异步”函数,它在许多外部调用上“等待”并返回带有结果的状态。 I have written a very basic test for an inner function 'dbResults'.我为内部函数“dbResults”编写了一个非常基本的测试。 However, I am unsure of how to go about testing if the entire controller function itself returns a certain value.但是,我不确定如何测试整个控制器函数本身是否返回某个值。 In the example below.在下面的例子中。 I was wondering if anyone can help me figure out what is the proper way to test the final result of a function such as 'getUserWithId'.我想知道是否有人可以帮助我弄清楚测试诸如“getUserWithId”之类的函数的最终结果的正确方法是什么。 The code written below is very close but not exactly what I have implemented.下面写的代码非常接近,但不完全是我实现的。 Any suggestions would be appreciated.任何建议,将不胜感激。

Controller控制器

export const MyController = {
  async getUserWithId(req, res) {
    let dbResults = await db.getOneUser(req.query.id);
    return res.status(200).json({ status: 'OK', data: dbResults });
  }
}

Current Test电流测试

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);
     });
   });
});

I would suggest using an integration-test for testing your controller rather than a unit-test .我建议使用integration-test来测试您的控制器而不是unit-test

integration-test threats the app as a black box where the network is the input (HTTP request) and 3rd party services as dependency that should be mocked (DB). integration-test将应用程序威胁为黑匣子,其中网络是输入(HTTP 请求),而 3rd 方服务是应该模拟的依赖项(DB)。

  • Use unit-test for services, factories, and utils.对服务、工厂和实用程序使用unit-test
  • Use integration-test for external interfaces like HTTP and WebSockets对 HTTP 和 WebSockets 等外部接口使用integration-test

You can add e2e-test as well but if you have only one component in your setup you integration-test will suffice.您也可以添加e2e-test ,但如果您的设置中只有一个组件,那么integration-test就足够了。

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

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