Reputation: 7474
When writing tests for React components using Jest & Enzyme, which tests should be responsible for making sure a component is given certain props?
<App>
<Somewhere>
<MyNestedComp someProps={someValue} />
</Somewhere>
</App>
In the example above, where should we test to make sure MyNestedComp is given the someProps prop. Currently, I test each of my components and am a bit confused sometimes as to where to test such specifics.
Upvotes: 0
Views: 246
Reputation: 24140
You should first start testing the component itself where you are passing the prop whether passed prop is available in the component itself or not, it's corresponding html rendered correctly or not.
You can use enzyme's shallow rendering to limit yourself to the specific component which you are testing.
e.g
Suppose in MyNestedComp I am using passed prop someProps
to display in some html element.
const MyNestedComp = ({someProps}) => {
return (
<div>
<h1>{someProps}</h1>
</div>
)
}
Unit test for MyNestedComp can be written as -
const wrapper = shallow(<MyNestedComp someProps={"someValue"} />);
expect(wrapper.html()).to.equal('<div><h1>someValue</h1></div>');
Then you can write test case for parent component as well which Somewhere
in your example.
You can check if prop passed from parent component reaches to child component correctly or not and many other test cases are possible.
<Somewhere>
<MyNestedComp someProps={someValue} />
</Somewhere>
Unit test case for Somewhere can be written as -
const wrapper = shallow(
<Somewhere>
<MyNestedComp someProps={someValue} />
</Somewhere>
);
const childWrapper = wrapper.find('MyNestedComp');
expect(childWrapper).to.have.length(1);
expect(wrapper.find({someProps: 'someValue'})).to.have.length(1);
expect(wrapper.prop('someProps')).to.equal("someValue");
I hope it helps you.
Upvotes: 1