[英]Checking props of a child component with shallow rendering using enzyme
I have a problem understanding shallow rendering of enzyme. 我在理解酶的浅层渲染时遇到了问题。
I have a component WeatherApplication
which has a child component CitySelection
. 我有一个组件WeatherApplication
,它有一个子组件CitySelection
。 The CitySelection
receives a property selectedCity
which is hold in the WeatherApplication
s state. 所述CitySelection
接收属性selectedCity
其是保持在WeatherApplication
S状态。
The component: 组件:
export default class WeatherApplication extends React.Component {
constructor(props) {
super(props);
this.state = {
city : "Hamburg"
}
}
selectCity(value) {
this.setState({
city: value
});
}
render() {
return (
<div>
<CitySelection selectCity={this.selectCity.bind(this)} selectedCity={this.state.city} />
</div>
);
}
}
I tested sussessfully that the CitySeleciton exists and that the selectedCity is "Hamburg" and the correct function is passed. 我毫不犹豫地测试了CitySeleciton存在并且selectedCity是“汉堡”并且正确的功能被传递。
Now I want to test the behaviour of the selectCity method. 现在我想测试selectCity方法的行为。
it("updates the temperature when the city is changed", () => {
var wrapper = shallow(<WeatherApplication/>);
wrapper.instance().selectCity("Bremen");
var citySelection = wrapper.find(CitySelection);
expect(citySelection.props().selectedCity).toEqual("Bremen");
});
This test fails, because the value of citySelection.props().selectedCity
is still Hamburg. 此测试失败,因为citySelection.props().selectedCity
值仍然是汉堡。
I checked that the render
method of WeatherApplication
is called again and this.state.city
has the correct value. 我检查了WeatherApplication
的render
方法是否再次被调用, this.state.city
具有正确的值。 But I cannot fetch it via the props. 但我无法通过道具获取它。
Calling wrapper.update()
after selectCity()
should do the trick: 在selectCity()
wrapper.update()
之后调用wrapper.update()
应该可以解决这个问题:
it("updates the temperature when the city is changed", () => {
var wrapper = shallow(<WeatherApplication/>);
wrapper.instance().selectCity("Bremen");
wrapper.update();
var citySelection = wrapper.find(CitySelection);
expect(citySelection.props().selectedCity).toEqual("Bremen");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.