Node.js环境下Koa2添加travis ci持续集成工具的方法
前言
因为最近使用koa2做项目测试开发,所以想整合下travisci,网上资料也比较少,于是自己就整了个,做个记录。分享出来供大家参考学习,下面来看看详细的介绍吧。
方法如下:
先来看下travis.yml的配置
language:node_js node_js: -"6" before_script: -./node_modules/.bin/knexmigrate:latest--knexfile='./app/knexfile.js' script: -npmruntest
因为是接口测试,所以首先需要做表创建等操作。
测试的命令:
NODE_ENV=productionNODE_CONFIG_DIR='./app/config/'./node_modules/.bin/mocha--require'babel-polyfill'--compilersjs:babel-register./app/test/**/*.js
主要是测试这里,使用了supertest,大概看下是如何调用的。
constrequest=require('supertest');
constshould=require('should');
constindex=require('../../index');
letapp=request(index.listen());
describe('/api/persons',function(){
letpersonId;
it('POST/api/persons-createpersonsuccessandrespondwith200',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){
returndone(err);
}
letresJson=JSON.parse(res.text);
personId=resJson.id;
done();
})
});
it('GET/api/persons-fetchpersonsitem',function(done){
app.get('/api/persons')
.expect(200)
.expect(function(res){
(res.body.length>0).should.be.true;
})
.end(function(err,res){
if(err){
returndone(err);
}
done();
})
});
it('GET/api/persons/:id-fetchaperson',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){
returndone(err);
}
done();
})
});
it('DELETE/api/persons/:id-deleteaperson',function(done){
app.delete(`/api/persons/${personId}`)
.expect(200)
.end(function(err,res){
if(err){
returndone(err);
}
done();
})
});
it('GET/api/persons/:id-fetchapersonshould404',function(done){
app.get(`/api/persons/${personId}`)
.expect(404)
.end(function(err,res){
if(err){
returndone(err);
}
done();
})
});
});
这里主要注意的是
constindex=require('../../index');
需要将koa实例暴漏出来,不然在做travisci的集成后,启动了项目,测试的时候依然找不到具体访问地址。
来看下我的index.js
importKnexfrom'knex';
import{
Model
}from'objection';
importknexConfigfrom'./knexfile';
importconfigfrom'config';
importKoafrom'koa';
importkoaLoggerfrom'koa-logger';
importbodyParserfrom'koa-bodyparser';
importrenderfrom'koa-ejs';
importcofrom'co';
importkoaStaticfrom"koa2-static"
importrouterfrom'./router';
constpath=require('path');
//initialknex
constknex=Knex(knexConfig.development);
Model.knex(knex);
//initialapp
constapp=newKoa();
//initialrender
render(app,{
root:path.join(__dirname+'/view'),
layout:'template',
viewExt:'ejs',
cache:true,
debug:true
});
app.context.render=co.wrap(app.context.render);
//initialstatic
app.use(koaLogger())
.use(bodyParser())
.use(router.routes())
.use(koaStatic({
path:'/web',
root:__dirname+"/../static"
}));
module.exports=app;
需要注意的是这里的
module.exports=app;
暴漏出来,再supertest中才可以独立启动server测试。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。