I can't for the life of me get Jest/Enzyme to play nicely with styled components.
I have a component I am mounting that filters out a list of 5 of the most recent shipments.
it("should have five shipments", () => {
const wrapper = shallow(<LastFiveShipments shipments={dummyProps.shipments} />);
wrapper.debug();
const styledList = wrapper.find("styled.ul");
expect(styledList).exists().to.equal(true);;
})
const LastFiveShipments = ({shipments}) => {
return (
<StyledList>
<h5>Last Five Shipments:</h5>
{
shipments.sort((a, b) => new Date(a.cargo_units[0].created_at) - new Date(b.cargo_units[0].created_at))
.filter((shipment, index) => index < 5)
.map((shipment, index) => <li key={index}>{shipment.reference}</li> )
}
</StyledList>
)
}
const StyledList = styled.ul`
padding: 1em;
margin: 0 10px;
background: #f0f0f0;
border-radius: 10px;
border: 1px solid #14374e;
margin: 1em 0;
& li {
text-align: center;
}
`;
styled.ul
is the displayName and find
is having no luck selecting it.
Shallow rendering is one way that Enzyme keeps tests simpler than Jest. When you shallow-render a component with Enzyme, you render only that component. Enzyme doesn't render any of the children of that component. This is a useful restriction that ensures that you aren't testing too much in one test.
Both Jest and Enzyme are meant to test the react applications. Jest can be used with any other Javascript framework, but Enzyme is meant to run on react only. Jest can be used without Enzyme, and snapshots can be created and tested perfectly fine. But the Enzyme adds additional functionality to it.
You can also rename your styled component to make it easier to read. For example
const StyledList = styled.ul`
padding: 1em;
margin: 0 10px;
background: #f0f0f0;
border-radius: 10px;
border: 1px solid #14374e;
margin: 1em 0;
& li {
text-align: center;
}
`;
StyledList.displayName = 'ul';
test.js
expect(wrapper.find('ul')).toHaveLength(1)
In that way, you don't need to import your styled component
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With