styled-components: V4: Unable to target name for styled component in tests, the name is always "ForwardRef"

Reproduction

https://codesandbox.io/s/yv7l2p76q9

Steps to reproduce

Write enzyme test for a styled component to ensure the correct components are rendered.

Expected Behavior

You should be able to target styled components by their name or explicitly set displayName

Actual Behavior

All styled components have the name ForwardRef instead of the name you give it, making it difficult to differentiate between them

Ideally, it would be nice if the functionality was the same as it was before, where it automatically took the name of whatever you named the styled component as. Most of the tests in our test suite use enzyme in this way and it would cause a considerable refactor to go through and either set an explicit displayName to each instance, or start using specific classes and apply them to all affected components.

Is there a better way of handling this situation?

Thank you!

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 2
  • Comments: 23 (11 by maintainers)

Most upvoted comments

Any progress on the Styled Component display Name? Or will enzyme fix this issue? Always show <StyledComponent> now. So a lots of Jest tests failed.

2

Thanks

Finding by displayName seems to be fixed in the latest enzyme + enzyme-adaptor-react-16.

This is separate from shallow mounting, but installing latest allowed me to target by displayName – meaning, find('MyComponentName'). In previous versions + styled-components 4 it would fail.

Awesome, thank you! I’ll try to upgrade soon and hopefully all will work as expected. Thanks again for all your help and followup with this!

@probablyup Thanks for all your help with this and your fast replies and follow ups! I’ll keep an eye out for the latest enzyme release and try upgrading when that’s available. Thanks again!

Thanks @probablyup, worked a treat!!! I ended up extending my Enzyme setup for the time being with:

enzyme.mountStyled = StyledComponent => {
  const renderedComponent = mount(StyledComponent);
  return renderedComponent.find(`.${StyledComponent.type.styledComponentId}`);
};

// so I can simply call this in all tests
mountStyled(<Component />);

Thanks again!