组件部分为以下结构时,需要虚拟store测试
import { connect } from 'react-redux'
class App extends Component { /* ... */ }
export default connect(mapStateToProps)(App)
- mock掉 action部分
import { setPerson, delPerson } from '../../src/store/action/person-action'
jest.mock('../../src/store/action/person-action');
- 创建虚拟store (redux官网测试部分案例)
//中间件功能
const thunk = ({ dispatch, getState }) => next => action => {
if (typeof action === 'function') {
return action(dispatch, getState)
}
return next(action)
}
//组件中有需要初始化的数据或者数据格式就写进去
const initialState = {
setPerson: {
itemLists: ['test']
}
};
//创建虚拟getState() dispatch()等
const create = () => {
const mockStore = {
getState: jest.fn(() => (initialState)),
dispatch: jest.fn(),
subscribe: jest.fn(),
}
const next = jest.fn()
const invoke = action => thunk(mockStore)(next)(action)
return { mockStore, next, invoke }
}
const { mockStore } = create();
- 使用
//测试组件中 点击事件后 某个action被成功调用
test('add person', () => {
let wrapper = mount(
<Provider store={mockStore}>
<Page3 />
</Provider>
);
let Page = wrapper.find('Page3');
Page.setState({ item: 'Jeff' });//修改组件中state的值,再发送点击事件传值
const btn = wrapper.find('button');
btn.simulate('click');
expect(setPerson).toBeCalledWith('Jeff');
})