阅读 214

Egg 单元测试

单元测试

在工作中,完成一个模块的 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


作者:tangxd3
链接:https://juejin.cn/post/7020611264921485325


文章分类
后端
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐