HelloWorld
1、创建controller
在/app/controller目录下新建文件hello.js
'use strict'; // 使用严格模式
const Controller = require('egg').Controller; // 引入依赖
class HomeController extends Controller {
async index() { // Egg.js全部使用异步模式 请注意这里是异步模式
const { ctx } = this; // 获取上下文 ctx也可以叫其他的名字但一般叫这个
ctx.body = '<h1>Hello World</h1>'; // 设置响应页面的报文体
}
}
module.exports = HomeController; // 将该controller暴露出去
2、设置路由
在/app目录下router.js文件内新增一行
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller } = app;
router.get('/', controller.home.index);
// get代表的是请求类型是get
// /hello 代表的是请求路径
// controller代表是controller文件夹下
// hello 代表 hello.js文件
// helloWorld 代表的是helloWorld异步方法
router.get('/hello', controller.hello.helloWorld);
};
3、保存启动
页面效果如图所示:
单元测试
同步单元测试
1、创建测试文件
2、测试代码
'use strict';
const { app } = require('egg-mock/bootstrap');
// describe方法有两个参数
// 第一个参数是对于测试的描述 例如:test app/controller/hello.test.js
// 第二个参数是一个回调函数 回(调函数就是一个被作为参数传递的函数)
describe('test /app/controller/hello.test.js', () => {
it('should GET /hello', () => {
return app.httpRequest()
// get请求 请求 /hello
.get('/hello')
// 请求返回页面数据为:<h1>Hello World</h1>
.expect('<h1>Hello World</h1>')
// 请求的状态为200
.expect(200);
});
});
使用命令测试:
结果展示:
异步方法
写异步单元测试,需要有一个异步的Controller方法。
'use strict'; // 使用严格模式
const Controller = require('egg').Controller; // 引入依赖
class Hello02Controller extends Controller {
async helloWorld02() { // egg.js要求必须使用异步模式
const { ctx } = this; // 获取上下文 ctx也可以叫其他的名字但一般叫这个
await new Promise(resolve => {
setTimeout(() => {
resolve(ctx.body = '<h1>EGG 向你走来</h1>');
}, 5000);
});
}
}
module.exports = Hello02Controller; // 将该controller暴露出去
运行结果:
异步单元测试
异步测试代码
'use strict';
const { app } = require('egg-mock/bootstrap');
describe('test /app/controller/hello02.test.js', () => {
it('test EGG', async () => { // 注意和上面的同步测试的差别async
await app.httpRequest() // 注意这里没有了return 多了await
.get('/hello02')
.expect(200)
.expect('<h1>EGG 向你走来</h1>');
});
});
测试命令:
测试结果: