说明:
自己是根据官网学习,可能自己话术并不好,也推荐大家先去官网学习
生成项目
//通过脚手架生成项目
$ egg-init egg_mock_demo --type=simple
....
[egg-init] usage:
- cd /Users/zhujiawei/egg/egg_mocha_demo
- npm install
- npm start / npm run dev / npm test
//执行npm i
可以发现 让我运行npm test,说明脚手架的项目已经有了单元测试的案例,虽然还不懂也执行一下看看
> egg-bin test
test/app/controller/home.test.js
✓ should assert
✓ should GET /
2 passing (669ms)
测试目录结构
为了让我们更多地关注测试用例本身如何编写,而不是耗费时间在如何运行测试脚本等辅助工作上,框架对单元测试做了一些基本约定
test
├── app
└── controller
└── home.test.js
Controller 测试
以下两个方法是对controller层以及router层的测试,
会访问/ 并跳转到对应的controller层 最后返回结果
describe('test/app/controller/home.test.js', () => {
it('should GET /', () => {
return app.httpRequest()
//访问 get /
.get('/')
//希望返回的结果
.expect('hi, egg')
//希望返回的状态
.expect(200);
});
// 使用generator function 方式写测试用例,可以在一个用例中串行发起多次请求
it('should send multi requests', async () => {
await app.httpRequest()
.get('/')
.expect('hi, egg')
.expect(200);
// 在请求一次
const result = await app.httpRequest()
.get('/')
.expect(200)
.expect('hi, egg');
assert(result.status === 200);
});
});
执行npm test
> egg_mocha_demo@1.0.0 test /Users/zhujiawei/egg/egg_mocha_demo
> npm run lint -- --fix && npm run test-local
> egg_mocha_demo@1.0.0 lint /Users/zhujiawei/egg/egg_mocha_demo
> eslint . "--fix"
> egg_mocha_demo@1.0.0 test-local /Users/zhujiawei/egg/egg_mocha_demo
> egg-bin test
test/app/controller/home.test.js
✓ should GET /
✓ should send multi requests
2 passing (672ms)
测试没有出什么问题
service 测试
service 相对于Controller来水,测试起来会更加简单,我们只需要先创建一个ctx,然后通过
ctx.service.${serviceName}拿到service实例,然后调用Service方法即可
- 编写service层
'use strict';
const Service = require('egg').Service;
class UserService extends Service {
async get(name) {
return name;
}
}
module.exports = UserService;
- 编写test
test/app/service/user.test.js
'use strict';
const { app, assert } = require('egg-mock/bootstrap');
describe('get()', () => {
it('should get exists user', async () => {
// 创建 ctx
const ctx = app.mockContext();
// 通过 ctx 访问到 service.user
const user = await ctx.service.user.get('fengmk2');
assert(user === 'fengmk2');
});
});
- 执行npm test
test/app/controller/home.test.js
✓ should GET /
✓ should send multi requests
get()
✓ should get exists user
成功~