带有样式组件的 Jest/Enzyme

Mar*_*ark 4 reactjs jestjs enzyme styled-components

我一生都无法让 Jest/Enzyme 与样式化组件完美搭配。

我有一个我正在安装的组件,它过滤掉了最近发货的 5 个列表。

  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);;
  })
Run Code Online (Sandbox Code Playgroud)
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;
  }
`;
Run Code Online (Sandbox Code Playgroud)

styled.ul是 displayName 并且find没有运气选择它。

Car*_*los 9

您还可以重命名样式化组件以使其更易于阅读。例如

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';
Run Code Online (Sandbox Code Playgroud)

测试.js

expect(wrapper.find('ul')).toHaveLength(1)
Run Code Online (Sandbox Code Playgroud)

这样,您就不需要导入样式化组件


Don*_*and 5

在这种情况下StyledList,您可以导入您正在搜索的组件,并使用它代替"styled.ul"

import StyledList from ''

wrapper.find(StyledList)
Run Code Online (Sandbox Code Playgroud)