Search code examples
jestjsstyled-componentsreact-testing-library

After upgrading styled-components to 6.0 toHaveStyle does not work


I am upgrading my styled-components from version 5 to the latest 6. And now my tests (jest+RTL) are failing due to the problem that .toHaveStyle stopped working. Instead I should use .toHaveStyleRule. Am I doing something wrong or is it by design?

My component is:

import React from "react";
import styled from "styled-components";

const DivBase = styled.div`
  align-items: center;
`;

export const Div = ({ children, ...rest }) => {
  return <DivBase {...rest}>{children}</DivBase>;
};

My test is:

it("renders with styled component", () => {
    const StyledDiv = styled(Div)`
      align-items: flex-end;
      justify-content: space-between;
    `;

    const component = render(
      <StyledDiv data-test={"test-id"}>
        <div>bla</div>
      </StyledDiv>,
    );

    const div = component.getByTestId(/test-id/i);

    // failing
    expect(div).toHaveStyle({
      alignItems: "flex-end",
      justifyContent: "space-between",
    });

    // success
    expect(div).toHaveStyleRule("align-items", "flex-end");
  });

Snapshot is:

exports[`renders with styled component`] = `
.c0 {
  align-items: center;
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
}

.c1 {
  align-items: flex-end;
  justify-content: space-between;
}

<div
  class="c0 c1"
  data-test="test-id"
>
  <div>
    bla
  </div>
</div>
`;

And screen.debug returns:

    <div
      class="sc-gsMHZj gOHtYd"
      data-test="test-id"
    >
      <div>
        bla
      </div>
    </div>

I can see that snapshot is setting class names like: c0, c1, etc. But RTL is rendering my div with these classes: sc-gsMHZj, gOHtYd. Is it correct? Still can not understand why .toHaveStyle used to work with version 5 but does not wor with the latest version 6?

Thank you


Solution

  • Using .toHaveStyleRule fixes this for the moment, so just use this instead of .toHaveStyle.

    There are multiple issues open in the styled-components repo on GitHub adressing this, but as far as I can see there's not an official fix for this yet.