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
是返回的状态码200
和 ctx.body
的值
编写完成之后,我们在控制台运行 yarn test
异步单元测试
在进行异步单元测试之前,我们需要先到 product.js
中, index
方法之后编写一个新的异步方法
在
app/controller/product.js
中index
结束后,添加如下代码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后出现)
当 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
作者:tangxd3
链接:https://juejin.cn/post/7020611264921485325