controller


一般情况下,Controller 下面的方法有异步也有同步的,但是 egg 规定里面的方法都是异步的

Controller 的使用

app/controller/user.js

  1. 'use strict';
  2. //Controller 类
  3. const Controller = require('egg').Controller;
  4. //继承
  5. class UserController extends Controller {
  6. async index() {
  7. const { ctx } = this;
  8. ctx.body = 'hi, user index';
  9. }
  10. async lists() {
  11. const { ctx } = this;
  12. await new Promise(resolve => {
  13. setTimeout(() => {
  14. resolve();
  15. }, 3000);
  16. });
  17. ctx.body = [{ id: 123 }];
  18. }
  19. }
  20. module.exports = UserController;

单元测试

test/app/controller/user.test.js

  1. 'use strict';
  2. const { app } = require('egg-mock/bootstrap');
  3. describe('test/app/controller/user.test.js', () => {
  4. it('user index', () => {
  5. return app
  6. .httpRequest()
  7. .get('/user')
  8. .expect(200)
  9. .expect('hi, user index');
  10. });
  11. it('user lists', async () => {
  12. await app
  13. .httpRequest()
  14. .get('/user/lists')
  15. .expect(200)
  16. .expect('[{"id":123}]');
  17. });
  18. });