单元测试一般不会只在本机执行,使用持续集成工具,每日进行自动化单元测试,对于JavaScript,需要在多个浏览器环境里执行,测试兼容性,我们需要知道多少测试用例没有通过,测试覆盖率等数据等。
1、参考文档
http://karma-runner.github.io/0.12/plus/jenkins.html
http://www.shenyanchao.cn/blog/2013/04/01/run-karma-in-jenkins-ci/
2、在Jenkins服务器上安装node.js
安装步骤参考
引用
3、配置测试相关的插件
在项目目录下打开命令行,执行
npm karma-chrome-launcher #chrome浏览器插件
npm karma-firefox-launcher #firefox浏览器插件
npm karma-junit-reporter #junit 测试报告插件
npm karma-coverage #单元测试覆盖率插件
4、修改配置文件karma.conf.js
添加测试结果报告和单元测试覆盖率
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '.',
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'js/*.js'
],
// list of files to exclude
exclude: [
'client/main.js'
],
preprocessors: {
'js/*.js':'coverage'
},
coverageReporter:{
type : 'cobertura',
dir : 'coverage/'
},
// use dots reporter, as travis terminal does not support escaping sequences
// possible values: 'dots', 'progress'
// CLI --reporters progress
reporters: ['dots', 'junit','coverage'],
junitReporter: {
// will be resolved to basePath (in the same way as files/exclude patterns)
outputFile: 'test-results.xml'
},
// web server port
// CLI --port 9876
port: 9876,
// enable / disable colors in the output (reporters and logs)
// CLI --colors --no-colors
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
// CLI --log-level debug
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
// CLI --auto-watch --no-auto-watch
autoWatch: true,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
// CLI --browsers Chrome,Firefox,Safari
//browsers: [process.env.TRAVIS ? 'Firefox' : 'Chrome'],
browsers: ['IE'],
// If browser does not capture in given timeout [ms], kill it
// CLI --capture-timeout 5000
captureTimeout: 20000,
// Auto run tests on start (when browsers are captured) and exit
// CLI --single-run --no-single-run
singleRun: true,
// report which specs are slower than 500ms
// CLI --report-slower-than 500
reportSlowerThan: 500,
plugins: [
'karma-jasmine',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-ie-launcher',
'karma-junit-reporter',
'karma-commonjs',
'karma-coverage'
]
});
};
其中junit report测试插件,会在当前项目目录下生成test-results.xml文件。
coverage覆盖率插件,会在当前目录下生成coverage目录,里面是覆盖率数据文件。
5、Jenkins安装插件
Jenkins Cobertura Plugin 测试覆盖率插件
6、在Jenkins上配置一个自由风格的任务
在源代码管理里,填写项目的SVN地址等,可以让Jenkins正常下载源码
7、构建命令
构建选Execute windows batch command
set Path=%Path%;D:\Program Files\nodejs\
set IE_BIN=C:\Program Files\Internet Explorer\iexplore.exe
node ./node_modules/karma/bin/karma start
8、测试选项
构建后操作
Publish Cobertura Coverage Report选项,
在Cobertura xml report pattern里填写
coverage/**/*.xml
Publish JUnit test result report选项
Test report XMLs里填写
test-results.xml
9、测试结果