最近用 Koa2 做專案測試開發,順手想把 Travis CI 接進來。網路上 Koa 的資料不多,於是邊試邊記錄成篇。
language: node_js node_js: - "6" before_script: - ./node_modules/.bin/knex migrate:latest --knexfile='./app/knexfile.js' script: - npm run test
因為做的是介面測試,必須先有資料表,所以 before_script 裡先跑一次 knex migration 建立結構,再執行測試。
NODE_ENV=production NODE_CONFIG_DIR='./app/config/' ./node_modules/.bin/mocha --require 'babel-polyfill' --compilers js:babel-register ./app/test/**/*.js
這裡用 supertest 對 Koa 應用發起真實 HTTP 請求,並以 should 做斷言:
const request = require('supertest');
const should = require('should');
const index = require('../../index');
let app = request(index.listen());
describe('/api/persons', function() {
let personId;
it('POST /api/persons - create person success and respond with 200', function(done) {
app.post('/api/persons')
.send({ 'firstName': 'Jennifer', 'lastName': 'Lawrence', 'age': 24 })
.expect(200)
.expect(function(res) {
(res.body.id > 0).should.be.true;
})
.end(function(err, res) {
if (err) { return done(err); }
let resJson = JSON.parse(res.text);
personId = resJson.id;
done();
})
});
it('GET /api/persons - fetch persons item', function(done) {
app.get('/api/persons')
.expect(200)
.expect(function(res) {
(res.body.length > 0).should.be.true;
})
.end(function(err, res) {
if (err) { return done(err); }
done();
})
});
it('GET /api/persons/:id - fetch a person', function(done) {
app.get(`/api/persons/${personId}`)
.expect(200)
.expect(function(res) {
(res.body.id == personId).should.be.true;
})
.end(function(err, res) {
if (err) { return done(err); }
done();
})
});
it('DELETE /api/persons/:id - delete a person', function(done) {
app.delete(`/api/persons/${personId}`)
.expect(200)
.end(function(err, res) {
if (err) { return done(err); }
done();
})
});
it('GET /api/persons/:id - fetch a person should 404', function(done) {
app.get(`/api/persons/${personId}`)
.expect(404)
.end(function(err, res) {
if (err) { return done(err); }
done();
})
});
});
這裡最關鍵的一行是:
const index = require('../../index');
也就是必須把 Koa 實例匯出。否則測試程式 require 進來什麼都拿不到,supertest 也就無從啟動伺服器進行驗證。
import Knex from 'knex';
import { Model } from 'objection';
import knexConfig from './knexfile';
import config from 'config';
import Koa from 'koa';
import koaLogger from 'koa-logger';
import bodyParser from 'koa-bodyparser';
import render from 'koa-ejs';
import co from 'co';
import koaStatic from "koa2-static"
import router from './router';
const path = require('path');
// initial knex
const knex = Knex(knexConfig.development);
Model.knex(knex);
// initial app
const app = new Koa();
// initial render
render(app, {
root: path.join(__dirname + '/view'),
layout: 'template',
viewExt: 'ejs',
cache: true,
debug: true
});
app.context.render = co.wrap(app.context.render);
// initial static
app.use(koaLogger())
.use(bodyParser())
.use(router.routes())
.use(koaStatic({ path: '/web', root: __dirname + "/../static" }));
module.exports = app;
最後一行 module.exports = app; 是整個整合的樞紐:匯出 app 但不呼叫 listen(),讓啟動與測試各自決定如何使用。正式上線時再由另一支進入點(例如 bin/www)負責 app.listen(port),測試則交給 supertest 自行開啟埠號,兩邊互不干擾。
把 Koa 接入 CI 的步驟就三件事:寫好 travis.yml 的 migration 與 test 階段、讓測試能取得 app 實例、確認測試會留下可重複執行的資料狀態。第三點特別容易被忽略——CI 每次都在全新的環境跑,但本地開發時資料庫往往已有殘留資料,這類差異最好用独立的測試資料庫隔離。