Testing: Finding styled emotion components with Jest/Enzyme

Viewed 891

I migrated a project from glamorous to emotion. The only missing puzzle piece? Testing.

In glamorous i could find elements with selectors like these:

$component.find('StyledComponent');

$component.find('StyledComponent[prop="value"]');

This does not work anymore. The best way i found so far is:

import StyledComponent from 'my/ui/StyledComponent';

$component.find(StyledComponent);

$component.find(StyledComponent).filter('[prop="value"]');

I liked the former way because it was not required to import the component at all. Some emotion components are defined in a file without exporting them. In those cases it would be even more verbose:

$component.find('div[className*="StyledComponent"]');

$component.find('div[className*="StyledComponent"][prop="value"]'); // or
$component.find('div[className*="StyledComponent"]').filter('[prop="value"]')

Is there a better way? Thanks for reading!

1 Answers

You could still use the first approach by setting the styled component's displayName when you define it.

const StyledComponent = styled('div')` // ... `;
StyledComponent.displayName = 'StyledComponent';

This will allow you to find during tests with the initial:

$component.find('StyledComponent');

I hope this helps.

Related