[Node.js基础]学习②①--Http测试

http://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/001489059908796ab910b35d443485aa064322863372732000

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 = `

Hello, ${name}!

`; }); 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, '

Hello, world!

'); }); it('#test GET /path?name=Bob', async () => { let res = await request(server) .get('/path?name=Bob') .expect('Content-Type', /text\/html/) .expect(200, '

Hello, Bob!

'); }); }); });

你可能感兴趣的:([Node.js基础]学习②①--Http测试)