目录
coverage
src
|__test.js
test
|__test.test.js
karma.conf.js
package.json
项目所需依赖 package.json
{
"devDependencies": {
"chai": "^4.1.2", // 断言库
"karma": "^2.0.0",
"karma-chai": "^0.1.0",
"karma-chrome-launcher": "^2.2.0", // 自动启用浏览器插件
"karma-coverage": "^1.1.1", // 测试代码覆盖率报告 插件
"karma-mocha": "^1.3.0",
"karma-mocha-reporter": "^2.2.5", // 命令行中 测试结果显示风格
"mocha": "^5.0.0",
// 让karma支持es6语法的依赖
"babel-plugin-transform-es2015-modules-umd": "^6.6.5",
"babel-preset-es2015": "^6.6.0",
"karma-babel-preprocessor": "^6.0.1",
}
}
karma的相关配置 karma.conf.js
module.exports = function(config) {
config.set({
// 告诉karma用的测试框架(mocha)和断言库 (karma-chai)
frameworks: ['mocha','chai'],
// 将功能代码和测试代码加载到karma
files: [
'src/**/*.js',
'test/**/*.spec.js'
],
// 检测文件变动 文件变动自动执行测试文件
autoWatch: true,
// 自动启用Chrome浏览器执行代码 karma-chrome-launcher
browsers: ['Chrome'],
// 测试报告的显示格式(命令行内的显示格式) karma-mocha-reporter
// 测试覆盖率报告 coverage
reporters: ['mocha', 'coverage'],
preprocessors: {
// source files, that you wanna generate coverage for
// do not include tests or libraries
// (these files will be instrumented by Istanbul)
'src/**/*.js': ['babel', 'coverage'],
'test/**/*.test.js': ['babel']
},
// 生成的覆盖率报告 配置项
coverageReporter: {
type : 'html',
dir : 'coverage/'
}
});
};
.babelrc配置
{
"presets": ["es2015"],
"plugins": ["transform-es2015-modules-umd"],
// 是用在babel编译时添加istanbul忽略,代码覆盖率能够清晰展示。
"auxiliaryCommentBefore": "istanbul ignore next"
}
test.js
function add(x, y) {
return x + y;
}
function asyn(a){
setTimeout(function(){
let b = 2;
b ++;
a(b)
})
}
export {add, async}
test.test.js
import * as test from '../src/test'
describe('加法函数的测试', function() {
it('1 加 1 应该等于 2', function() {
expect(test.add(1,1)).to.equal(2);
});
});
describe('测试异步', () => {
it('2秒后2等于3',(done) => {
test.asyn((b) => {
expect(b).to.be.equal(3);
done();
})
})
})
相关网站
有关karma:(https://github.com/karma-runner/karma)
karam所有插件:(https://www.npmjs.com/browse/keyword/karma-plugin)
本文项目地址:(https://github.com/liuxinya/Karma-Mocha)
网友评论