使用酶通过浅层渲染检查子组件的道具 [英] Checking props of a child component with shallow rendering using enzyme
问题描述
我在理解酶的浅层提炼时遇到问题.
I have a problem understanding shallow rendering of enzyme.
我有一个组件 WeatherApplication
,其中有一个子组件 CitySelection
. CitySelection
接收属性 selectedCity
,该属性保存在 WeatherApplication
的状态下.
I have a component WeatherApplication
which has a child component CitySelection
.
The CitySelection
receives a property selectedCity
which is hold in the WeatherApplication
s state.
组件:
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>
);
}
}
我怀疑地测试了CitySeleciton的存在,并且selectedCity是汉堡"并且传递了正确的功能.
I tested sussessfully that the CitySeleciton exists and that the selectedCity is "Hamburg" and the correct function is passed.
现在我要测试selectCity方法的行为.
Now I want to test the behaviour of the selectCity method.
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");
});
此测试失败,因为 citySelection.props().selectedCity
的值仍然是Hamburg.
This test fails, because the value of citySelection.props().selectedCity
is still Hamburg.
我检查是否再次调用了 WeatherApplication
的 render
方法,并且 this.state.city
的值正确.但是我无法通过道具来获取它.
I checked that the render
method of WeatherApplication
is called again and this.state.city
has the correct value. But I cannot fetch it via the props.
推荐答案
在 selectCity()
之后调用 wrapper.update()
应该可以解决问题:
Calling wrapper.update()
after selectCity()
should do the trick:
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");
});
这篇关于使用酶通过浅层渲染检查子组件的道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!