Egg 单元测试

1,314 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

本文已参与 「掘力星计划」 ,赢取创作大礼包,挑战创作激励金。

A journey of a thousand miles begins with single step

持续更新中...

系列文章传送门:

单元测试

在工作中,完成一个模块的 Controller 之后,都需要编写对应的测试文件,进行单元测试,以便于快速发现逻辑中的问题,尽快解决。单元测试分为同步单元测试和异步单元测试。

同步单元测试

在上文中,我们编写了 product.js 文件,本文我们对 product.js 中的 index 方法编写同步单元测试

test/app/controller 中创建 product.test.js 文件用于编写 product.js 文件的单元测试

代码如下

'use strict';

const { app } = require('egg-mock/bootstrap');

describe('test/app/controller/product.tets.js', () => {
  it('product index', () => {
    return app.httpRequest()
      .get('/product') //此处内容为index方法的路由
      .expect(200)
      .expect('product page'); // 此处内容和index方法的返回相同
  });
});

describe 方法第一个参数是该文件的路径,第二个参数是一个箭头函数

it 方法第一个参数是对那个方法进行编写单元测试,第二个参数是一个箭头函数,get 的内容是该方法的路由,expect 是返回的状态码200ctx.body 的值

编写完成之后,我们在控制台运行 yarn test

procuct-index

异步单元测试

在进行异步单元测试之前,我们需要先到 product.js 中, index 方法之后编写一个新的异步方法

  • app/controller/product.jsindex结束后,添加如下代码

    async getPrice() {
      const { ctx } = this;
      await new Promise(resolve => {
        setTimeout(() => {
          resolve(ctx.body = 'The price of this product is $50');
        }, 5000);
      });
    }
    
  • app/router.js 中配置上面方法的路由地址

    router.get('/getPrice', controller.product.getPrice);
    
  • 效果(加载5s后出现)

    getPrice

getPrcie 方法编写完成之后,回到test/app/controller/product.test.js 文件。进行编写异步单元测试

  • 在同步单元测试方法后添加

    it('product getPrice', async () => {
      await app.httpRequest()
        .get('/getPrice')
        .expect(200)
        .expect('The price of this product is $50');
    });	
    
  • 编写完成之后,我们在控制台运行 yarn test

    product-getPrice

写在最后

关注我,更多内容持续输出

🌹 喜欢就点个赞吧👍🌹

🌹 觉得有收获的,可以来一波 收藏+关注,以免你下次找不到我😁🌹

🌹欢迎大家留言交流,批评指正,转发请注明出处,谢谢支持!🌹