Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting, while mapping uncaught exceptions to the correct test cases. Hosted on GitHub.
$ npm install mocha
$ mkdir test
$ $EDITOR test/test.js # or open with your favorite editor
然后在你的编辑器写下以下代码:
var assert = require('assert');
describe('Array', function() {
describe('#indexOf()', function() {
it('should return -1 when the value is not present', function() {
assert.equal(-1, [1,2,3].indexOf(4));
});
});
});
使用以下命令开始测试:
$ ./node_modules/mocha/bin/mocha
终端会显示以下信息:
Array
#indexOf()
✓ should return -1 when the value is not present
1 passing (9ms)
describe('User', function() {
describe('#save()', function() {
it('should save without error', function(done) {
var user = new User('Luna');
user.save(function(err) {
if (err) done(err);
else done();
});
});
});
});
describe('User', function() {
describe('#save()', function() {
it('should save without error', function(done) {
var user = new User('Luna');
user.save(done);
});
});
});
Enzyme is a JavaScript Testing utility for React that makes it easier to assert, manipulate, and traverse your React Components' output.
Enzyme's API is meant to be intuitive and flexible by mimicking jQuery's API for DOM manipulation and traversal.
在实习的过程中做过还算比较多的项目,但是几乎都由于时间原因没有在真正项目中写过单元测试脚本。很久之前接触过
Mocha
,既然测试驱动开发是一种良好的开发实践模式,自己也在个人小项目中使用过Mocha
,有空写下这篇文章。这是我在前段时间写的微信小程序音乐播放器中写的一段单元测试脚本。
Mocha简介
在Mocha官方是这样介绍它的:
即
Mocha
是一种既可运行在Node.js
也可运行在浏览器中的富JavaScript
测试框架,并可以让您很方便地进行异步测试。它可以较为严格地测试您的JavaScript
语句是否有你所期待的输出结果。其实,使用测试驱动开发将会大大简化编写代码的思考过程,并使它变得更加简单,更加快捷。但是仅仅编写测试是远远不够的,真正重要的东西是了解编写测试的类型以及如何组织代码来符合测试的模式。这才是我们测试的真正目的。
安装方法:
您也可以把它安装在您的项目中
简单入门:
然后在你的编辑器写下以下代码:
使用以下命令开始测试:
终端会显示以下信息:
您可以在
package.json
文件中进行测试代码的相关配置:然后在终端执行以下命令
Mocha
甚至可以较为方便地进行异步代码的测试。它可以在你的异步操作完成之际调用你的回调函数从而完成测试。通过向it()
添加一个名为done()
的回调函数,Mocha
便能自动等待异步执行完毕时再调用回调函数,从而完成测试。我们甚至可以这么写,让编写异步脚本测试显得更加简单一些。
done()
函数是能够自动处理error
的。当然,回调函数这种ES5的写法显得也是有点low吧。项目中也许你会返回一个
Promise()
对象。以下这些API能够比较方便地处理Promise()
所处理的异步请求。断言库Chai
Mocha
配合断言库Chai可以让我们更加方便地进行单元测试脚本的编写。Chai
是一个较为简洁的断言库,主要有以下三种方法:用supertest模拟http请求测试后端接口
在最开始我给出的那段代码中,我便是使用了
supertest
模块来模拟http
请求,并使用Mocha
测试了我的Node.js
服务接口。主要用了是对于返回报文中状态码的判断以及相关数据的判等。
用Enzyme测试React前端页面
在Enzyme官方是这样描述的
即
Enzyme
是一个专门为React
设计的JavaScript
测试框架。它能很方便地断言你的React组件
。Enzyme
的API通过模仿jQuery
的DOM相关API,操作遍历你的DOM节点,简单快捷地测试你的React
组件。安装方法:
使用方法: 通过将你的组件渲染成真实DOM节点,通过DOM相关API进行测试操作。
Shallow Rendering
里,一个组件就是一个单元!保证了子组件的相关行为并不会影响到父组件的测试!而以下是一个
Shallow Rendering
的例子:更多关于Shallow Rendering API可移步官方文档。
与
Shallow Rendering
相反是的,Full DOM Rendering
是一种较为理想的方式。它会真正地将你的组件挂载到DOM容器上,所有组件都会有完全的生命周期(如componentDidMount
),并且组件之间的行为将会相互影响。而以下是一个
Full DOM Rendering
的例子:更多关于Full DOM Rendering可移步官方文档。
Static Rendering
会将React
组件的render
方法调用一次,并返回静态的HTML模板。