package.json
{
"name": "koa-test",
"version": "1.0.0",
"description": "Test Koa 2 app",
"main": "start.js",
"scripts": {
"start": "node --use_strict start.js",
"test": "mocha"
},
"keywords": [
"koa",
"async",
"mocha",
"test"
],
"author": "Michael Liao",
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "https://github.com/michaelliao/learn-javascript.git"
},
"dependencies": {
"koa": "2.0.0"
},
"devDependencies": {
"mocha": "3.0.2",
"supertest": "3.0.0"
}
}
app.js
const Koa = require('koa');
const app = new Koa();
app.use(async (ctx, next) => {
const start = new Date().getTime();
await next();
const ms = new Date().getTime() - start;
console.log(`${ctx.request.method} ${ctx.request.url}: ${ms}ms`);
ctx.response.set('X-Response-Time', `${ms}ms`);
});
app.use(async (ctx, next) => {
var name = ctx.request.query.name || 'world';
ctx.response.type = 'text/html';
ctx.response.body = `<h1>Hello, ${name}!</h1>`;
});
module.exports = app;
start.js
const app = require('./app');
app.listen(3000);
console.log('app started at port 3000...');
test目录
app-test.js
const
request = require('supertest'),
app = require('../app');
describe('#test koa app', () => {
let server = app.listen(9900);
describe('#test server', () => {
it('#test GET /', async () => {
let res = await request(server)
.get('/')
.expect('Content-Type', /text\/html/)
.expect(200, '<h1>Hello, world!</h1>');
});
it('#test GET /path?name=Bob', async () => {
let res = await request(server)
.get('/path?name=Bob')
.expect('Content-Type', /text\/html/)
.expect(200, '<h1>Hello, Bob!</h1>');
});
});
});