一步一步实现现代前端单元测试

今天我们一步一步把各种不同的技术结合一起来完成页面的单元测试和 e2e 测试。

1 karma + mocha + power assert

karma是一款测试流程管理工具,包含在执行测试前进行一些动作,自动在指定的环境(可以是真实浏览器,也可以是PhantamJS 等 headless browser)下运行测试代码等功能。
mocha测试框架,类似的有 jasminejest 等。个人感觉 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

生成的配置文件略作修改,如下(因篇幅原因,隐藏了注释):


                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值