【发布时间】:2019-01-27 07:42:53
【问题描述】:
所以我想用 Enzyme/Jest 测试 mapStateToProps 和 mapDispatchToProps。
我有一个像这样的组件 DrawerAvatar:
DrawerAvatar.js
const mapStateToProps = state => ({
isAuthenticated: state.authReducer.isAuthenticated
});
export default compose(
connect(mapStateToProps, null)
)(DrawerAvatar);
DrawerAvatar.test.js
import configureMockStore from 'redux-mock-store';
import connectedDrawerAvatar, { DrawerAvatar } from './DrawerAvatar';
const mockStore = configureMockStore();
it('mapStateToProps should return the right value', () => {
const initialState = {
someState: 123
};
const store = mockStore(initialState);
const wrapper = shallow(<connectedDrawerAvatar store={store} />);
expect(wrapper.props().someState).toBe(123);
});
但是,这不起作用,因为 wrapper.props().someState 返回 undefined... 所以我不知道如何使用连接的组件测试 mapStatesToProps 和 redux-mock-store。
我也不知道如何测试 mapDispatchToProps ..! 我已经尝试过blog 中提供的方法,但它不起作用。
非常感谢!
编辑: 这可行,但我不确定它是否真的测试 mapStateToProps...有人可以确认这是测试 mapStateToProps 的正确方法吗? DrawerAvatar.test.js
it('mapStateToProps should return the right value', () => {
const initialState = {
isAuthenticated: false
};
const mockStore = configureMockStore();
const store = mockStore(initialState);
const wrapper = shallow(<connectedDrawerAvatar store={store} />);
expect(wrapper.props().store.getState().isAuthenticated).toBe(false);
});
【问题讨论】:
-
看看使用 mount 而不是 shallow 并查看允许您传递上下文的第二个参数
-
我已经检查过了,但我真的不明白上下文到底是什么......你能提供一些代码 sn-p 来说明你的想法吗?
-
mapDispatchToProps测试可以查看stackoverflow.com/a/55814950/1897654
标签: reactjs redux react-redux jestjs enzyme