【发布时间】:2018-12-27 07:52:03
【问题描述】:
我的父组件根据状态 { conditionMet : true } 呈现一个 <Child1 /> 组件。
如何编写一个测试来检查子组件本身的呈现,而不是组件内字符串的呈现?我想避免使用setTimeout()。
这是我如何构建测试的问题吗?或者,我是如何构建组件的? Jest / Enzyme 中是否存在阻止检查子组件是否已呈现的已知限制或错误?
反应:16.6.3 开玩笑:23.6.0 酶:3.7.0 Enzyme-adapter-react-16
ParentComponent 的 Jest 单元测试:
describe('ParentComponent', () => {
test('renders Child1 component when conditionMet is true', () => {
const parentMount = mount(<ParentComponent />);
const param1 = "expected value";
const param2 = true;
parentMount.instance().checkCondition(param1, param2); // results in Parent's state 'conditionMet' === 'true'
//This is not working - the length of the Child1 component is always 0
expect(parentMount.find(Child1)).toHaveLength(1);
//This alternate option passes, but it's not testing the rendering of the component!
expect(parentMount.text()).toMatch('Expected string renders from Child1');
});
});
ParentComponent.js
class ParentComponent extends Component {
constructor(props) {
super(props);
this.state = {
conditionMet: false
};
}
checkCondition = (param1, param2) => {
if (param1 === 'expected value' && param2 === true)
{
this.setState({conditionMet: true});
} else {
this.setState({conditionMet: false});
}
this.displayChildComponent();
}
};
displayChildComponent() {
if (this.state.conditionMet) {
return(
<Child1 />
)
}
else {
return(
<Child2 />
)
}
}
render() {
return (
<div className="parent-container">
{this.displayChildComponent()}
</div>
);
}
}
【问题讨论】:
标签: javascript reactjs jestjs enzyme