简体   繁体   中英

“No style rules found on passed Component” when unit testing direct child of styled component using react-testing-library

Here is the styled li for my component:

const Tab = styled.li`
  margin: 0px 60px;
  color: black;
  & > button {
    border: none;
    padding: 28px 0px;
    font-weight: 600px;
  }
`;

And here is the unit test that's failing:

const tabItems = [
  {
    label: 'Test 1',
    id: 'tab1',
  },
  {
    label: 'Test 2',
    id: 'tab2',
  },
];
describe('Tabs styling tests', () => {
  afterEach(cleanup);

  it('should have font-weight 600', async () => {
    const { getByText } = render(<Tabs tabItems={tabItems} selected="test1" />);

    expect(getByText('Test 1')).toHaveStyleRule('font-weight', '600');
  });
});

I am getting No style rules found on passed Component for any css style that I try to test for that button.

The tests pass for any .parentElement styling that is tested.
For eg. expect(getByText('Test 1').parentElement).toHaveStyleRule('color', 'black'); works just fine.

How do I test the direct child of a styled component?

Figured out how to get this to work finally:

it('should have font-weight 600', async () => {
  const { getByText } = render(<Tabs tabItems={tabItems} selected="test1" />);

  expect(getByText('Test 1').parentElement).toHaveStyleRule(
    'font-weight', 
    '600',
    { modifier: css`> button` }
  );
});

Source: https://github.com/styled-components/jest-styled-components/blob/master/README.md#tohavestylerule

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM