Mark
Mark

Reputation: 1679

Jest/Enzyme with styled components

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.

Upvotes: 6

Views: 7165

Answers (3)

Jitender
Jitender

Reputation: 7969

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

Upvotes: 11

Matt Carlotta
Matt Carlotta

Reputation: 19762

@Donovan beat me to it.

Anyway, I was able to replicate the same problem, however, there are two workarounds:

  1. Instead of using shallow, you can mount the component and then assert: expect(wrapper.find("StyledComponent > ul")).toHaveLength(1);.
  2. Instead of mounting the component, you can import StyledList from 'path/to/styledList'; and then assert: expect(wrapper.find(StyledList)).toHaveLength(1)

Working example:

Edit Styled Component

Upvotes: 1

Donovan Hiland
Donovan Hiland

Reputation: 1499

You can import the component you're searching for, in this case StyledList, and use it instead of "styled.ul"

import StyledList from ''

wrapper.find(StyledList)

Upvotes: 6

Related Questions