Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. The CitySelection receives a property selectedCity which is hold in the WeatherApplications state.

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.

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

});

This test fails, because the value of citySelection.props().selectedCity is still Hamburg.

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.

like image 761
Ria Avatar asked Nov 03 '16 10:11

Ria


1 Answers

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");    
});
like image 82
Alexandr Lazarev Avatar answered Oct 19 '22 05:10

Alexandr Lazarev