const ADD_TODO = 'ADD_TODO'; const DEL_TODO = 'DEL_TODO'; let INIT_STATE = [{id:1,text:'1'},{id:2,text:'2'}]; function reducer(state=INIT_STATE,action={}){ switch(action.type){ case ADD_TODO: return [...state,action.todo]; case DEL_TODO: return state.filter(item=>item.id != action.id); default: return state; } } module.exports = reducer;
创建reducer.spec.js
let reducer = require('./reducer'); const ADD_TODO = 'ADD_TODO'; const DEL_TODO = 'DEL_TODO'; describe('reducer',()=>{ let INIT_STATE = [{id:1,text:'1'},{id:2,text:'2'}]; it('初始状态',()=>{ expect(reducer(undefined,{})).toEqual(INIT_STATE); }); it('增加todo',()=>{ let todos = reducer(INIT_STATE,{type:ADD_TODO,todo:{id:3,text:'3'}}); expect(todos).toEqual([...INIT_STATE,{id:3,text:'3'}]); }); it('删除todo',()=>{ let todos = reducer(INIT_STATE,{type:DEL_TODO,id:2}); expect(todos).toEqual([{id:1,text:'1'}]); }); });
2.6 测试点击事件
import React from 'react'; import Enzyme,{shallow} from 'enzyme'; import TodoItem from './TodoItem'; import Adapter from 'enzyme-adapter-react-16'; import { wrap } from 'module'; Enzyme.configure({adapter:new Adapter()}); //http://airbnb.io/enzyme/docs/api/ShallowWrapper/find.html //http://airbnb.io/enzyme/docs/api/selector.html describe('TodoItem',function(){ it('todo',()=>{ const wrapper = shallow(); expect(wrapper.text()).toMatch(/1/); expect(wrapper.hasClass('todo')).toBe(true); expect(wrapper.hasClass('todo-selected')).toBe(false); }); it('todo-selected',()=>{ const wrapper = shallow(); expect(wrapper.text()).toMatch(/1/); wrapper.simulate('click'); expect(wrapper.hasClass('todo')).toBe(false); expect(wrapper.hasClass('todo-selected')).toBe(true); }); });
2.7 mount
mount将React组件加载为真实的DOM
.get(index):返回指定位置的子组件的DOM节点
.at(index):返回指定位置的子组件
.text():返回当前组件的文本内容
.html():返回当前组件的HTML代码形式
.props():返回根组件的所有属性
.prop(key):返回根组件的指定属性
.state([key]):返回根组件的状态
import React from 'react'; import Enzyme,{mount} from 'enzyme'; import TodoApp from './TodoApp'; import Adapter from 'enzyme-adapter-react-16'; Enzyme.configure({adapter:new Adapter()}); describe('TodoApp',function(){ it('addTodo',()=>{ let wrapper = mount(); let len = wrapper.find('li').length; wrapper.find('button').at(0).simulate('click'); expect(wrapper.find('li').length).toBe(len + 1); }); it('delTodo',()=>{ let wrapper = mount(); let len = wrapper.find('li').length; wrapper.find('button').at(1).simulate('click'); expect(wrapper.find('li').length).toBe(len - 1); }); });