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)
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
MyComponent.test.js
Output
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.