Reputation: 17
I'm trying to test an if
condition with props. It works fine if I pass in this.props.thingToTest
but if I assign something like const propsVariable = this.props.thingToTest
and test the if
condition, I won't get code coverage.
I've tried passing in the const as props in my shallow wrapper, or declaring the const in the test but it still doesn't see it.
Component code:
render() {
const propsVariable = this.props.thingToTest;
if (this.props.otherThingToTest === 'test') {
return <Component />;
} else {
if (propsVariable) {
return <OtherComponent />;
}
}
}
Test code:
const props = {
propsVariable: {}
}
it('tests else condition in render method', () => {
const wrapper = shallow(<OriginalComponent {...props} />);
const instance = wrapper.instance();
jest.spyOn(instance, 'render');
instance.render();
expect(instance.render).toHaveBeenCalled();
});
I expect the else case to get hit and return <OtherComponent />
but it doesn't hit the else case at all.
If I put otherThingToTest
in the props object in my test it'll hit the first if
case fine, but because my other prop thingToTest
is assigned to a variable, it won't hit the else case and I'm not sure how to test that.
Upvotes: 1
Views: 764
Reputation: 2483
Since you have not passed thingToTest
props to the component in Test code, propsVariable
will be assigned undefined.
const propsVariable = this.props.thingToTest; // propsVariable = undefined
That's why code will not take the if
path inside the else
block and hence return <OtherComponent />;
statement will not covered.
So you need to just pass thingToTest
props to the component in Test code and it will work fine.
const props = {
thingToTest: 'someValue'
// passing propsVariable: {} won't work
// since it will be available as
// "this.props.propsVariable" inside the
// component
}
Note: else
case will hit if you don't pass otherThingToTest
props.
Upvotes: 1