Skip to content

toHaveStyleRule with @media rule breaks after styled-components update #430

Open
@jkettmann

Description

@jkettmann

We recently updated styled-components to v6 and something caused some of our tests to fail. I was able to reproduce the issue in this repository (you can also run it here on Replit). Here's the example test:

import 'jest-styled-components';
import { render, screen } from '@testing-library/react';
import { styled } from 'styled-components';

const StyledDiv = styled.div`
  @media (min-width: 400px) {
    color: red;
  }
`;

function MyComponent() {
  return <StyledDiv data-testid="styled-div" />;
}

describe('toHaveStyleRule media test', () => {
  test('has red color on larger devices', async () => {
    render(<MyComponent />);

    const styledDiv = screen.getByTestId('styled-div');
    expect(styledDiv).toHaveStyleRule('color', 'red', {
      media: '(min-width: 400px)',
    });
  });
});

This is the error I'm getting:

CleanShot 2023-07-31 at 17 34 29

The problem seems to be that this check in toHaveStyleRule rule[option] === options[option].replace(/:\s/g, ":") is not working anymore.

const getAtRules = (ast, options) => {
  return Object.keys(options)
    .map((option) =>
      ast.stylesheet.rules
        .filter((rule) => rule.type === option && rule[option] === options[option].replace(/:\s/g, ":"))
        .map((rule) => rule.rules)
        .reduce((acc, rules) => acc.concat(rules), [])
    )
    .reduce((acc, rules) => acc.concat(rules), []);
};

Before rule.option didn't have a whitespace. I'm not sure what changed but now it looks like this:

CleanShot 2023-07-31 at 17 28 58

I'm happy to create a PR but as I said, I'm not sure what the original cause of the whitespace not being removed is.

Edit: To run the tests in the Replit simply run npm run test.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions