Finding Styled Components with Enzyme

Finding a styled component using enzyme's .find() can be a bit awkward. Consider the following example where we have a styled component which extends a Button component.

import Button from './button';

const MyButton = styled(Button)`
  /* styles */
`;

const MyComponent = (props) => (
  /* jsx */
    <MyButton />
  /* jsx */
);

export default MyComponent;

To find the button we need to access the button as ‘Styled(Button)’.

// test file

const wrapper = enzyme.shallow(<MyComponent />);

const myButton = wrapper.find('Styled(Button)');

This is not only awkward, it is also brittle as if the implementation of MyButton changes and it extends a different component then the name we need to find the button with will change and break the test.

const MyButton = styled(NewButton)`
  /* styles */
`;

// findable with .find('Styled(NewButton)');

To solve this problem and make the test more readable we can directly set the displayName of the styled component to a set name which does not depend on the implementation of the component.

const MyButton = styled(Button)`
  /* styles */
`;

MyButton.displayName = 'MyButton';

// findable with .find('MyButton');
Tags: Styled Components