Targeting styled components with enzyme's .find()
See original GitHub issueWhen I use styled-components to make “building block” components defined in the same file as the “assembled” component, I am having a really difficult time targeting them in my tests using enzyme’s .find()
method.
For example, with this styled-component:
import ImportedComponent from './ImportedComponent';
const Demo = styled.div`
`;
const Label = styled.span`
`;
const Thing = () =>
<Demo>
<ImportedComponent />
<Label />
<Label />
<Label />
</Demo>;
If I use an imported styled-component like <ImportedComponent>
, I can easily find it like with enzyme like:
describe('<Thing />', () => {
it('should contain an ImportedComponent', () => {
const wrapper = shallow(<Thing />);
const importedComponent = wrapper.find('ImportedComponent');
expect(importedComponent).to.have.length(1);
});
});
But I haven’t found an elegant way to find the “building block” components like <Label />
because they can’t be found by the component name as they appear more generically like “<styled.span>”. Is there a way for these “building block” components to appear with their component name like they are when imported? I don’t want to resort to targeting them by html or css as that is more brittle.
Issue Analytics
- State:
- Created 6 years ago
- Comments:13 (3 by maintainers)
Top GitHub Comments
This alternative described is to override the default styled component’s
displayName
:In render:
And then in testing:
t.equals(wrapper.find('MessageText').children().text(), 'Hello World');
For future readers, you don’t need to use a selector to find a styled component. You can simply import the styled component itself to find it. Modifying the original example to do this: