4
votes

Im testing using react-testing-library and jest-styled-components.

I have a wrapper component that renders the styles of its child button dependant on a selected prop passed to it.

This is the code:

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}
            `
          : ""}
    }
  }
`;

and the test

  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");

  });

but its failing with "Property 'background-position' not found in style rules" which is true for the original button, however when its parent is passed the selected prop this style applies.

I am also doing snapshot testing with the component however not testing the props getting passed brings the test coverage down.

Can anyone help?

1

1 Answers

0
votes

In general as far as nested styles testing is concerned, I would recommend testing directly the nested element.

I personally haven't figured out a way to test nested styles using the .toHaveStyle(``); (not even a simple

a {
  text-decoration: none;
}

)

so I ended up querying for the exact component I wanted to test, eg:

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

In your specific case I believe the way to go is to render your component in your test directly with the props that trigger the styles you want for each case (selected in your code example).