【问题标题】:How to test style of nested component jest-styled-components如何测试嵌套组件的样式 jest-styled-components
【发布时间】:2020-01-24 17:07:43
【问题描述】:

我正在使用 react-testing-library 和 jest-styled-components 进行测试。

我有一个包装器组件,它根据传递给它的选定道具呈现其子按钮的样式。

这是代码:

const selectedStyles = css`
  background-image: url(../image);
  background-position: center;
  background-repeat: no-repeat;
  border-color: ${color.grey6};
  height: 38px;
  width: 58px;
  & span {
    display: none;
  }
`;

const ButtonWrapper = styled.div`
  & button {
    font-size: 15px;
    line-height: 20px;
    padding: 8px 12px;
    ${props =>
      props.selected
        ? css`
            ${selectedStyles}
          `
        : ""}

    &:hover,
    :focus {
      ${props =>
        props.selected
          ? css`
              ${selectedStyles}
            `
          : ""}
    }
  }
`;

和测试

  test("it renders the correct styles when selected ", () => {
    const { container } = render(<CheckButton selected>Add</CheckButton>);
    const button = container.querySelector("button");
    expect(button).toHaveStyleRule("background-position", "center");

  });

但它与 "Property 'background-position' not found in style rules" 失败,这对于原始按钮是正确的,但是当它的父级传递选定的道具时,此样式适用。

我也在对组件进行快照测试,但是不测试通过的道具会降低测试覆盖率。

谁能帮忙?

【问题讨论】:

    标签: jestjs styled-components react-testing-library


    【解决方案1】:

    一般而言,就嵌套样式测试而言,我建议直接测试嵌套元素。

    我个人还没有找到使用.toHaveStyle(``); 测试嵌套样式的方法(甚至不是简单的

    a {
      text-decoration: none;
    }
    

    )

    所以我最终查询了我想要测试的确切组件,例如:

    expect(screen.getByText(/text-within-the-child-component/i)).toHaveStyle(`
       text-decoration: none;
    `);
    

    在您的具体情况下,我相信要走的路是直接在您的测试中使用触发每种情况所需样式的道具(在您的代码示例中为selected)来呈现您的组件。

    【讨论】:

      猜你喜欢
      • 2020-05-01
      • 2019-05-02
      • 2021-06-02
      • 2018-04-29
      • 1970-01-01
      • 2019-05-11
      • 2018-09-14
      • 2021-07-16
      • 2021-10-31
      相关资源
      最近更新 更多