【问题标题】:Jest/Enzyme with styled components带有样式组件的 Jest/Enzyme
【发布时间】:2019-08-23 05:49:00
【问题描述】:

我这辈子都无法让 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);;
  })
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 是 displayName,find 没有运气选择它。

【问题讨论】:

    标签: reactjs jestjs enzyme styled-components


    【解决方案1】:

    您可以导入您正在搜索的组件,在本例中为 StyledList,并使用它来代替 "styled.ul"

    import StyledList from ''
    
    wrapper.find(StyledList)
    

    【讨论】:

    • 它是组件内部的样式化 ul。
    • 您可以导出样式化的组件,以便在您的测试中将其导入并用于.find
    【解决方案2】:

    @Donovan 打败了我。

    无论如何,我能够复制同样的问题,但是,有两种解决方法:

    1. 您可以使用mount 组件,然后断言:expect(wrapper.find("StyledComponent &gt; ul")).toHaveLength(1);,而不是使用shallow
    2. 你可以import StyledList from 'path/to/styledList';而不是mounting组件,然后断言:expect(wrapper.find(StyledList)).toHaveLength(1)

    工作示例

    【讨论】:

      【解决方案3】:

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

      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)
      

      这样,你不需要导入你的样式化组件

      【讨论】:

        猜你喜欢
        • 2019-05-30
        • 2019-09-24
        • 2017-02-12
        • 2021-01-08
        • 2020-01-27
        • 2017-07-16
        • 2020-04-17
        • 2018-03-31
        • 2018-10-16
        相关资源
        最近更新 更多