今天我们一步一步把各种不同的技术结合一起来完成页面的单元测试和 e2e 测试。
1 karma + mocha + power assert
karma是一款测试流程管理工具,包含在执行测试前进行一些动作,自动在指定的环境(可以是真实浏览器,也可以是PhantamJS 等 headless browser)下运行测试代码等功能。
mocha测试框架,类似的有 jasmine 和 jest 等。个人感觉 mocha 对异步的支持和反馈信息的显示都非常不错。
power asser断言库,特点是 No API is the best API
。错误显示异常清晰,自带完整的自描述性。
```
1) Array #indexOf() should return index when the value is present:
AssertionError: # path/to/test/mocha_node.js:10
assert(ary.indexOf(zero) === two)
| | | | |
| | | | 2
| -1 0 false
[1,2,3]
[number] two
=> 2
[number] ary.indexOf(zero)
=> -1
```
以下所有命令假设在 test-demo 项目下进行操作。
1.1 安装依赖及初始化
# 为了操作方便在全局安装命令行支持
~/test-demo $ npm install karma-cli -g
# 安装 karma 包以及其他需要的插件和库,这里不一一阐述每个库的作用
~/test-demo $ npm install karma mocha power-assert karma-chrome-launcher karma-mocha karma-power-assert karma-spec-reporter karma-espower-preprocessor cross-env -D
# 创建测试目录
~/test-demo $ mkdir test
# 初始化 karma
~/test-demo $ karma init ./test/karma.conf.js
执行初始化过程按照提示进行选择和输入
Which testing framework do you want to use ?
Press tab to list possible options. Enter to move to the next question.
> mocha
Do you want to use Require.js ?
This will add Require.js plugin.
Press tab to list possible options. Enter to move to the next question.
> no
Do you want to capture any browsers automatically ?
Press tab to list possible options. Enter empty string to move to the next question.
> Chrome
>
What is the location of your source and test files ?
You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js".
Enter empty string to move to the next question.
>
Should any of the files included by the previous patterns be excluded ?
You can use glob patterns, eg. "**/*.swp".
Enter empty string to move to the next question.
>
Do you want Karma to watch all the files and run the tests on change ?
Press tab to list possible options.
> no
生成的配置文件略作修改,如下(因篇幅原因,隐藏了注释):