Karma 自动化测试框架搭建文档
一.前言
此文档为前端自动化单元测试框架 Karma
的搭建以及使用文档。
二.准备环境
先列出我们此次搭建测试框架 Karma
必须的环境和包。
1. node.js (node 引擎)
2. npm (node 包管理器)
3. cnpm(可选) (淘宝镜像)
4. karma (提供 web 服务和浏览器适配)
5. mocha (单元测试框架)
6. chai (断言库)
6. requirejs (提供非commonjs规范的模块加载)
7. karma-mocha karma-chai karma-requirejs (karma 中对应的包)
8. karma-chrome-launcher karma-ie-launcher (karma 中的浏览器适配包)
9. karma-mocha-reporter (karma 中的 mocha 终端测试报告)
10. karma-htmlfile-reporter (karam 生成 html 格式的测试报告文件)
三.安装步骤
1. 安装 node
和 npm
进入node官网,根据你的操作系统选择对应的安装包。安装时记得添加选择默认添加环境变量和安装npm
。
安装完成后打开gitbash
输入以下命令测试是否安装成功:
$ node -v
v10.14.1
$ npm -v
6.4.1
2. 安装 cnpm
此为npm
的淘宝镜像,为了解决npm
下载包网速过慢的问题。请在gitbash
中输入以下命令:
$ npm install -g cnpm --registry=https://registry.npm.taobao.org
完成后输入以下命令测试cnpm
是否安装成功:
cnpm -v
3.初始化 package.json
首先,在项目内新建一个文件夹 /test
。(与static
,templates
平级)。此时我们有以下目录结构:
由于这是我已经配置好的目录结构,各位可以先不用关心细节,我们从空的/test
文件夹开始。
在 gitbash
中进入 /test
目录,然后输入命令:
$ npm init -y
会出现一个名为 package.json
的 json
文件,文件内容如下:
4. 安装 karma
和 karma-cli
什么是 karma
这种问题大家可以自行去Karma官网自行查看。
我们回到刚刚那个 gitbash
目录,输入以下命令:
$ cnpm install karma-cli -g
$ cnpm install karma -D
安装好之后输入 karma --version
来查看是否安装成功。
5.安装 package.json
中的依赖
打开你的 package.json
文件,此时它的内容如下:
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"karma": "^4.0.0"
}
}
devDependencies
中是你的依赖包,现在你要做的就是用下面这个 json
中的内容去替换你的 package.json
内容。
{
"name": "test-project2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"chai": "^4.2.0",
"karma": "^4.0.0",
"karma-chai": "^0.1.0",
"karma-chrome-launcher": "^2.2.0",
"karma-htmlfile-reporter": "^0.3.7",
"karma-ie-launcher": "^1.0.0",
"karma-mocha": "^1.3.0",
"karma-mocha-reporter": "^2.2.5",
"karma-requirejs": "^1.1.0",
"mocha": "^5.2.0",
"requirejs": "^2.3.6"
}
}
替换完了后,回到 gitbash
中输入:
$ cnpm install
安装完成后即可。
5.初始化 karma.conf.js
配置文件
现在我们需要配置一下 karma
的配置文件:
$ karma init
然后 karma
会让我们配置一些选项,你可以按下面这张图来配:
完成后我们可以在 /test
文件夹根目录里看到一个 karma.conf.js
文件。
注意,在 windows
操作系统下使用 gitbash
进行 karma init
时会报以下错误:
这时你切换到 windows
的默认终端来执行命令就好。
由于不同的项目文件目录的配置不同,所以提供一个标准的 karma.conf.js
配置不是一件现实的事情,它需要对 karma.conf.js
文件中的 files
属性进行一些改变。下面我提供一个控制中心 RC2
版本的 karma.conf.js
配置:
// Karma configuration
// Generated on Mon Jan 28 2019 14:56:31 GMT+0800 (GMT+08:00)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha', 'requirejs', 'chai'],
// list of files / patterns to load in the browser
files: [
{ pattern: 'lib/*.js', included: true },
{ pattern: '../static/js/common/*.js', included: true },
{ pattern: 'unit-test/**/*.spec.js', included: false },
'./test-main.js'
],
// list of files / patterns to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['mocha', 'html'],
mochaReporter: {
output: 'autowatch'
},
htmlReporter: {
outputFile: 'reproter/units.html',
// Optional
pageTitle: 'Unit Tests',
subPageTitle: 'A sample project description',
groupSuites: true,
useCompactStyle: true,
useLegacyStyle: true
},
// web server port
port: 9877,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome', 'IE'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
6.设置 requirejs
入口文件
通常来说我们需要在 A.js
中引入 B.js
中的一个函数,需要这样:
const add = require('./B.js');
add(1,2) // logs 3
B.js
中的内容应该如下:
exports.add = function(){
var sum = 0;
for(let i = 0; i < arguments.length; i++){
sum += arguments[i];
}
return sum;
}
具体规则大家可以自行去查阅commonJS规范
。
但是我们现在不具备这个条件,前端代码并不是commonjs
格式,所以我们需要引入requirejs
来解决这个问题。
在 /test
文件夹下新建 test-main.js
文件,内容如下:
var TEST_REGEXP = /(spec|test)\.js$/i;
var allTestFiles = [];
// Get a list of all the test files to include
Object.keys(window.__karma__.files).forEach(function(file) {
if (TEST_REGEXP.test(file)) {
// Normalize paths to RequireJS module names.
// If you require sub-dependencies of test files to be loaded as-is (requiring file extension)
// then do not normalize the paths
var normalizedTestModule = file.replace(/^\/base\/|\.js$/g, '');
allTestFiles.push(normalizedTestModule);
}
});
require.config({
// Karma serves files under /base, which is the basePath from your config file
baseUrl: '/base',
// example of using a couple of path translations (paths), to allow us to refer to different library dependencies, without using relative paths
paths: {
},
// example of using a shim, to load non AMD libraries (such as underscore)
shim: {
'underscore': {
exports: '_'
}
},
// dynamically load all test files
deps: allTestFiles,
// we have to kickoff jasmine, as it is asynchronous
callback: window.__karma__.start
});
7.进行简单的 unit test
我以控制中心RC2
的目录结构为例,在 /webui/static/js/common
下有个datahandle.js
文件,我们取其中的一个dataHandle.cutLargeNum()
函数来进行测试。
首先看下目前 /test
的目录结构:
/reporter
是生成测试报告的文件夹,这个在后面再说。
注意这个 /unit-test
文件夹,这个文件夹名字并非是固定的,只要你能把它和 karma.conf.js
中 files
的路径名称对应起来。
我们在 /unit-test
文件夹下创建 index.spec.js
文件,注意,以后此文件夹下所有的测试用例文件都应该以 **.spec.js
结尾,应该我们在 karma.conf.js
和 test-main.js
文件中都做了正则限制。
index.spec.js
文件内容如下:
var expect = chai.expect;
describe('unit test', function(){
it('dataHandle.cutLargeNum(1000) = 1.00万',function(){
expect(dataHandle.cutLargeNum(10000)).to.equal('1.00万');
})
})
chai
为断言库,文中使用的是 BDD
风格的 expect
断言。
我们在 gitbash
中输入 $ karma start
运行测试,有以下输出结果:
我们还可以修改 karma.conf.js
中的 singleRun
属性为 false
:
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
然后再运行 $ karma start
,此时你再修改 /static/js/common
下的任何一个 js 文件, karma
都会自动重新运行 /unit-test
下的测试用例。
8.生成测试报告
生成测试报告的模块我选择的是 karma-htmlfile-reporter
,相应需要做的配置我已经加在之前的 karma.conf.js
文件中了。
我们只需要执行 $ karma start --reporter html
,就可以发现 /test
目录多了一个 /reporter
文件夹,里面放着我们的测试报告 units.html
。
大概长这样: