2年前写过一篇文章用Karma和QUnit做前端自动单元测试,只是大概讲解了 karma 如何使用,针对的测试情况是传统的页面模式。本文中题目中【现代】两字表明了这篇文章对比之前的最大不同,最近几年随着SPA
(Single Page Application) 技术和各种组件化解决方案(Vue/React/Angular)的普及,我们开发的应用的组织方式和复杂度已经发生了翻天覆地的变化,对应我们的测试方式也必须跟上时代的发展。现在我们一步一步把各种不同的技术结合一起来完成页面的单元测试和 e2e 测试。
1 karma + mocha + power assert
- karma - 是一款测试流程管理工具,包含在执行测试前进行一些动作,自动在指定的环境(可以是真实浏览器,也可以是 PhantamJS 等 headless browser)下运行测试代码等功能。
- mocha - 测试框架,类似的有 jasmine 和 jest 等。个人感觉 mocha 对异步的支持和反馈信息的显示都非常不错。
power assert - 断言库,特点是
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
生成的配置文件略作修改,如下(因篇幅原因,隐藏了注释):
module.exports = function(config) {
config.set({
basePath: '',
// 表示可以在测试文件中不需引入即可使用两个库的全局方法
frameworks: ['mocha', 'power-assert'],
files: [
'