fil*_*yoo 5 reactjs jestjs redux enzyme react-redux
所以,我想测试mapStateToProps,并mapDispatchToProps与酶/玩笑。
我有一个像这样的DrawerAvatar组件:
DrawerAvatar.js
const mapStateToProps = state => ({
isAuthenticated: state.authReducer.isAuthenticated
});
export default compose(
connect(mapStateToProps, null)
)(DrawerAvatar);
Run Code Online (Sandbox Code Playgroud)
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);
});
Run Code Online (Sandbox Code Playgroud)
但是,这不起作用,因为会wrapper.props().someState返回undefined...因此,我不知道如何使用连接的组件来测试mapStatesToProps和redux-mock-store。
我也不知道怎么测试mapDispatchToProps ..!我已经尝试了此博客中提供的方法,但是它不起作用。
非常感谢你 !
编辑:这有效,但是我不确定它是否真的测试了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);
});
Run Code Online (Sandbox Code Playgroud)
import React from 'react';
import { shallow } from 'enzyme';
import configureMockStore from 'redux-mock-store';
import ConnectedDrawerAvatar from './DrawerAvatar';
describe('DrawerAvatar', ()=> {
const mockStore = configureMockStore();
it.each([true, false], 'receives correct value from store as props', (value)=> {
const initialState = { authReducer: { isAuthenticated: value } }
const store = mockStore(initialState)
const wrapper = shallow(<ConnectedDrawerAvatar store={store} />)
expect(wrapper.props().isAuthenticated).toBe(value)
})
})
Run Code Online (Sandbox Code Playgroud)
最简单的测试方法是直接使用 mapStateToProps,如下所示:
export const mapStateToProps = state => ({
isAuthenticated: state.authReducer.isAuthenticated
});
Run Code Online (Sandbox Code Playgroud)
并进行这样的测试:
it('mapStateToProps should return the right value', () => {
const mockedState = {
authReducer: {
isAuthenticated: false
}
};
const state = mapStateToProps(mockedState);
expect(state).toBeFalsy();
});
Run Code Online (Sandbox Code Playgroud)
但我真的不明白为什么你应该这样做。
IMO 你不应该测试连接的组件。只需导出容器类,直接测试即可。
人们不应该测试组件连接的原因是它在库本身中经过了很好的测试,因此通过测试您并没有真正增加任何价值。
| 归档时间: |
|
| 查看次数: |
5048 次 |
| 最近记录: |