styled-components / jest-styled-components

🔧 💅 Jest utilities for Styled Components
MIT License
1.58k stars 145 forks source link

toHaveStyleRule does not detect inline styles with jest and react-testing-library #295

Open ncesar opened 4 years ago

ncesar commented 4 years ago

If I create a styled component with a color of black, and then, when using the component, if I pass a conditional inline style, toHaveStyleRulewill detect only the first color.

const StyledValue = styled(ListItemText)`
  flex: 1;
  display: flex;
  color: black;
`;
        <StyledValue
          className='list-value'
            style: {
              fontSize: '32px',
              lineHeight: '36px',
              fontFamily: 'CentraleSansLight',
              color: isCaution(styledItemProps)
                ? 'yellow'
                : 'blue'
            }
        />
  it('should render the LatestDataListItem with any caution', () => {
    const { getByTestId } = renderWithThemeProvider(
      <LatestDataListItem /* this component is part of StyledValue */
        data-test-id={testId}
        record={{ ...mockRecord, caution: 'any' }}
      />
    );
    const el = getByTestId(testId);
    expect(el.querySelector('.list-value .list-item-text').toHaveStyleRule('color', 'yellow');
    /* expect(el.querySelector('.list-value .list-item-text').style.color).toBe(
      'yellow' */ //This was the solution.
    );
  });

If I use debug, in the DOM the component has the correct inline style, but not in the test.

"jest-styled-components": "^6.3.3"
"@testing-library/jest-dom": "^4.1.2",
"@testing-library/react": "^9.1.2"
"jest-styled-components": "^6.3.3"
rebirthtobi commented 4 years ago

i am also experiencing this even after using container.firstChild

aleksandr-omise commented 4 years ago

Somehow i start getting this error after i renamed component and test file, renamed to kebab-case.

matthieubessol commented 3 years ago

I'm also getting this after renaming my Component, I had to switch back to get it work :/

benschac commented 3 years ago

SAME

benschac commented 3 years ago

This makes sense now. jest-styled-components isn't compatible with react-testing-library. If you want to test if an element has a style on it:

it('should have flex', () => {
    expect(component).toHaveStyle({
      display: 'flex',
    });
  });

worked for me after adding and configuring.