gpt4 book ai didi

reactjs - 使用 enzyme 检查具有浅渲染的子组件的 Prop

转载 作者:行者123 更新时间:2023-12-03 13:26:07 24 4
gpt4 key购买 nike

我在理解 enzyme 的浅层渲染时遇到问题。

我有一个组件WeatherApplication,它有一个子组件CitySelectionCitySelection 接收一个属性 selectedCity,该属性保存在 WeatherApplication 的状态中。

组件:

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 是“Hamburg”并且传递了正确的函数。

现在我想测试 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");

});

此测试失败,因为 citySelection.props().selectedCity 的值仍然是汉堡。

我检查了 WeatherApplicationrender 方法是否被再次调用,并且 this.state.city 具有正确的值。但我无法通过 props 获取它。

最佳答案

selectCity() 之后调用 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");
});

关于reactjs - 使用 enzyme 检查具有浅渲染的子组件的 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40399026/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com