Unit testing Jest/酶-未在React Redux容器上设置道具
我对开玩笑/酶和反应还不熟悉,我正在尝试测试一个容器组件 我的测试是检查道具是否与initialState匹配 这是我的组件Unit testing Jest/酶-未在React Redux容器上设置道具,unit-testing,react-redux,enzyme,jestjs,Unit Testing,React Redux,Enzyme,Jestjs,我对开玩笑/酶和反应还不熟悉,我正在尝试测试一个容器组件 我的测试是检查道具是否与initialState匹配 这是我的组件 import React, { Component } from 'react'; import { connect } from 'react-redux'; import { loadHomeAction } from '../../actions/home'; export class Home extends Component { componentDi
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { loadHomeAction } from '../../actions/home';
export class Home extends Component {
componentDidMount() {
this.props.dispatch(loadHomeAction());
}
render() {
const { content, loading } = this.props.home;
return (
<div>
<div>{loading && <p>Loading...</p>}</div>
<div>{!loading && content.map(item => <p key={item.message}>{item.message}</p>)}</div>
</div>
);
}
}
const mapStateToProps = ({ home }) => ({ home });
export default connect(mapStateToProps)(Home);
在注销容器时,我可以看到home未定义
我不明白这是如何/为什么不起作用的
我一直在关注这篇博文,试图了解如何测试这些连接的组件-
编辑
好的,我对我的测试做了一些更改,我的设置函数现在看起来像
function setup(props = {}, state = {}) {
const mockStore = configureStore();
const store = mockStore(state);
const wrapper = shallow(<Home {...props} />);
const container = shallow(
<Provider store={store}>
<ConnectedHome />
</Provider>
);
return { wrapper, container };
}
it('should match props with initial state', () => {
const { container } = setup({}, initialState);
expect(container.props().home).toEqual(initialState);
});
现在我从控制台得到这个
TypeError: Cannot destructure property `content` of 'undefined' or 'null'.
编辑#2
通过添加
我的测试现在有效。但我觉得我基本上说的是1=1 在我看来,您不应该仅仅为了使类可测试而导出它。我发布了一个更简洁的解决方案,作为对类似问题的回答。请看这里:
另外,为了回答你的问题,我的建议是:
it('componentDidMount应分派loadHomeAction',()=>{
常量包装器=浅();
wrapper.instance().componentDidMount();
expect(wrapper.instance().props.dispatch).toBeCalledWith(loadHomeAction());
});代码>在我看来,您不应该仅仅为了使类可测试而导出它。我发布了一个更简洁的解决方案,作为对类似问题的回答。请看这里:
另外,为了回答你的问题,我的建议是:
用于测试渲染方法
分别测试组件安装方法
如何测试组件并安装它?给你:
it('componentDidMount应分派loadHomeAction',()=>{
常量包装器=浅();
wrapper.instance().componentDidMount();
expect(wrapper.instance().props.dispatch).toBeCalledWith(loadHomeAction());
});代码>
it('should match props with initial state', () => {
const { container } = setup({}, initialState);
expect(container.props().home).toEqual(initialState);
});
TypeError: Cannot destructure property `content` of 'undefined' or 'null'.