samedi 24 août 2019

How do I test the behavior of a function inside a component?

How do I test a function inside a component? (It affects the output of the function)

I have a function shouldRender that determines whether the component should be rendered. I have tried mounting the function and manually setting the props and state necessary but the function doesn't seem to be called correctly.

class MyComponent extends Component {
    shouldComponentRender(myProp, myState) {
        return myProp && myState;
    }

    render() {
        const shouldRender = shouldComponentRender(this.props.shouldRender, this.state.shouldRender);
        return (
            <React.Fragment>
                {shouldRender && <div> .... <div>}
            </React.Fragment>
        )
    }
}

Test code:

const wrapper = mount(<MyComponent />);
wrapper.setProps({shouldRender: true});
wrapper.setState({shouldRender: true});
expect(wrapper.find(".someClassThatShouldExistIfItWorked").length).to.equal(1);

I'm using mount because I wanted to see something in componentDidMount but that's unrelated to this question.

The error I get at the last line is:

    AssertionError: expected 0 to equal 1

Aucun commentaire:

Enregistrer un commentaire