jest-styled-components: Styles not found on a component (toHaveStyleRule)

With the latest enzyme (3.4.1) and jest-styled-components (6.0.0), the toHaveStyleRule assertion is not finding the styles on a component.

Symptoms:

    No style rules found on passed Component

      28 |         .dive()
      29 |         .dive()
    > 30 |     ).toHaveStyleRule('text-align', 'center')
      31 |   })
      32 |

Also visible in snapshots. Before, the snapshot included the style classes definition, e.g.:

.c0 {
  padding-left: 0;
 ...
  display: table-cell;
}

With the latest enzyme, in the snapshot, the className is still there on a component (twice?), but the class definition is missing:

<MyComponent
  centre={false}
  className="c0"
  className="... obnHq"

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 32 (7 by maintainers)

Most upvoted comments

I think I found the pattern that breaks after updating to version 6. It occurs when the styled component is (shallow) rendered by another component (which is the one being tested). Here’s an example:

MyComponent.js

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

const Card = styled.div`
  opacity: 1;
`;

const MyComponent = () => (
  <Card></Card>
);

export default MyComponent;

MyComponent.test.js

import React from 'react';
import { shallow } from 'enzyme';

import MyComponent from '../MyComponent';

describe('<MyComponent />', () => {
  it('renders with style rule', () => {
    const wrapper = shallow(<MyComponent />);
    console.log(wrapper.debug());
    expect(wrapper.find('MyComponent__Card')).toHaveStyleRule('opacity', '1');
  });
});

Output

  No style rules found on passed Component

       8 |     const wrapper = shallow(<MyComponent />);
       9 |     console.log(wrapper.debug());
    > 10 |     expect(wrapper.find('MyComponent__Card')).toHaveStyleRule('opacity', '1');
         |                                               ^
      11 |   });
      12 | });
      13 | 

In case anyone comes here because they have the same issue, I hit this from having two versions of styled-components in my node_modules (Lerna multimodule with a yarn workspace - there was a hoisted version and a version local to one module).

Thanks for your comment, @jmacioszek.

The test says “No style rules found on passed Component” because you are shallow rendering and the children components don’t get resolved. If you use mount, the tests will work. However, they would still fail because you need to see fluid={true}.

I hope this helps.

For anyone else running into this, my issue was styled-components not being hoisted in my monorepo.

I had dev and peer dependencies misconfigured in a couple packages, so there were two versions being referenced depending what package I was importing from. Check your node_modules folders in each package.

You should only see one copy of styled components hoisted to the root node_modules of of your monorepo.