github地址: https://github.com/thesecondlight/egg_mysql egg连接数据库,其中index.js是一个简单的单元测试文件。
首先在controller中新建文件index.js
'use strict';
const Controller = require('egg').Controller;
class indexController extends Controller {
async index() {
this.ctx.body = 'hi,egg';
}
}
module.exports = indexController;
service中新建index.js
'use strict';
const Service = require('egg').Service;
class UserService extends Service {
async get(name) {
return name;
}
}
module.exports = UserService;
测试文件目录test,与app文件夹同一级
test/app/controller/index.test.js (命名规则:测试文件名.test.js) 对controller层以及router层的测试
'use strict';
const { app, assert } = require('egg-mock/bootstrap');
describe('test/app/controller/index.test.js', () => {
it('should GET /', () => {
return app.httpRequest()
.get('/index') //router访问路径
.expect('hi,egg') //希望返回的结果
.expect(200); //希望返回的状态
});
it('should send multi requests', async () => {
await app.httpRequest()
.get('/index')
.expect('hi,egg')
.expect(200);
const result = await app.httpRequest()
.get('/index')
.expect(200)
.expect('hi,egg');
assert(result.status === 200);
});
});
运行npm test
可能会报错,因为你router路径的不规范,访问了不存在的路径,或者无效变量的存在,看错误提示,进行相应的修改即可。
test/app/service/index.test.js
'use strict';
const { app, assert } = require('egg-mock/bootstrap');
describe('get()', () => {
it('should get exists user', async () => {
const ctx = app.mockContext(); //创建ctx
const user = await ctx.service.index.get('yumu'); //通过ctx访问到service.user
assert(user === 'yumu');
});
});
运行npm test