一般情况下,Controller 下面的方法有异步也有同步的,但是 egg 规定里面的方法都是异步的
Controller 的使用
app/controller/user.js
'use strict';
//Controller 类
const Controller = require('egg').Controller;
//继承
class UserController extends Controller {
async index() {
const { ctx } = this;
ctx.body = 'hi, user index';
}
async lists() {
const { ctx } = this;
await new Promise(resolve => {
setTimeout(() => {
resolve();
}, 3000);
});
ctx.body = [{ id: 123 }];
}
}
module.exports = UserController;
单元测试
test/app/controller/user.test.js
'use strict';
const { app } = require('egg-mock/bootstrap');
describe('test/app/controller/user.test.js', () => {
it('user index', () => {
return app
.httpRequest()
.get('/user')
.expect(200)
.expect('hi, user index');
});
it('user lists', async () => {
await app
.httpRequest()
.get('/user/lists')
.expect(200)
.expect('[{"id":123}]');
});
});