使用样例:
import React from 'react';
import {expect} from 'chai';
import {shallow} from 'enzyme';
import TestComponent from '../components/TestComponent';
describe('Test TestComponent', () => {
// 创建一个虚拟的组件
const wrapper = shallow(
<TestComponent num={10} />/
);
/*
* 之后,我们可以:
* 通过wrapper.state()拿到组件的state
* 通过wrapper.instance()拿到组件实例,以此调用组件内的方法
* 通过wrapper.find()找到组件内的子组件
* 但是,无法通过wrapper.props()拿到组件的props
*/
// 测试该组件组外层的class
it('should render with currect wrapper', () => {
expect(wrapper.is('.test_component')).to.equal(true);
});
// 测试该组件初始化的state
it('should render with currect state', () => {
expect(wrapper.state()).to.deep.equal({
clickNum: 10
});
});
// 测试组件的方法
it('should add one', () => {
wrapper.instance().handleClick();
expect(wrapper.state()).to.deep.equal({
clickNum: 11
});
});
});
  Test Redux
  redux身为纯函数,非常便于mocha进行测试
// 测试actions
import * as ACTIONS from '../redux/actions';
describe('test actions', () => {
it('should return an action to create a todo', () => {
let expectedAction = {
type: ACTIONS.NEW_TODO,
todo: 'this is a new todo'
};
expect(ACTIONS.addNewTodo('this is a new todo')).to.deep.equal(expectedAction);
});
});
// 测试reducer
import * as REDUCERS from '../redux/reducers';
import * as ACTIONS from '../redux/actions';
describe('todos', () => {
let todos = [];
it('should add a new todo', () => {
todos.push({
todo: 'new todo',
complete: false
});
expect(REDUCERS.todos(todos, {
type: ACTIONS.NEW_TODO,
todo: 'new todo'
})).to.deep.equal([
{
todo: 'new todo',
complete: false
}
]);
});
});
// 还可以和store混用
import { createStore, applyMiddleware, combineReducers } from 'redux';
import thunk from 'redux-thunk';
import chai from 'chai';
import thunkMiddleware from 'redux-thunk';
import * as REDUCERS from '../redux/reducers';
import defaultState from '../redux/ConstValues';
import * as ACTIONS from '../redux/actions'
const appReducers = combineReducers(REDUCERS);
const AppStore = createStore(appReducers, defaultState, applyMiddleware(thunk));
let state = Object.assign({}, AppStore.getState());
// 一旦注册会时刻监听state变化
const subscribeListener = (result, done) => {
return AppStore.subscribe(() => {
expect(AppStore.getState()).to.deep.equal(result);
done();
});
};
describe('use store in unittest', () => {
it('should create a todo', (done) => {
// 首先取得我们的期望值
state.todos.append({
todo: 'new todo',
complete: false
});
// 注册state监听
let unsubscribe = subscribeListener(state, done);
AppStore.dispatch(ACTIONS.addNewTodo('new todo'));
// 结束之后取消监听
unsubscribe();
});
});
  基于 phantomjs 和selenium的UI UnitTest
  PhantomJS 是一个基于webkit的服务器端JavaScript API,即相当于在内存中跑了个无界面的webkit内核的浏览器。通过它我们可以模拟页面加载,并获取到页面上的DOM元素,进行一系列的操作,以此来模拟UI测试。但缺点是无法实时看见页面上的情况(不过可以截图)。
  而 Selenium 是专门为Web应用程序编写的一个验收测试工具,它直接运行在浏览器中。 Selenium 测试通常会调起一个可见的界面,但也可以通过设置,让它以 PhantomJS 的形式进行无界面的测试。
  · open 某个 url
  · 监听 onload 事件
  · 事件完成后调用 sendEvent 之类的 api 去点击某个 DOM 元素所在 point
  · 触发交互
  · 根据 UI 交互情况 延时 setTimeout (规避惰加载组件点不到的情况)继续 sendEvent 之类的交互