使用酶检查具有浅渲染的子组件的props

IT技术 reactjs jasmine enzyme
2021-05-22 05:28:56

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

我有一个组件WeatherApplication,它有一个子组件CitySelectionCitySelection接收特性selectedCity是保持在WeatherApplicationS状态。

组件:

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>
        );
    }
}

我 sussessfully 测试了 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仍然是汉堡。

我检查了再次调用render方法WeatherApplicationthis.state.city具有正确的值。但是我无法通过props获取它。

1个回答

调用wrapper.update()selectCity()应该可以解决问题:

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");    
});
其它你可能感兴趣的问题