问题
I want to test a simple Material UI select form which uses a FormControl and is exported withStyles. My Test case is pretty simple, i want to assert for example that my component renders an child. I try the following assertion:
expect(wrapper.find('InputLabel')).toEqual(true);
However, this assertion fails simply because the InputLabel is wrapped inside WithStyles AND WithFromControlContext (see debug output) :
<WithStyles(FormControl) id="my-control-id">
<WithStyles(WithFormControlContext(InputLabel)) htmlFor="my-control-id">
My Control Label
</WithStyles(WithFormControlContext(InputLabel))>
...
</WithStyles(FormControl)>
Is there any way to just test for the existence of the InputLabel child ignoring all the HOC components which are wrapped around it?
回答1:
In addition to wrapper.find()
, Enzyme offers wrapper.findWhere() - give it a function, and it returns every node in the render tree for which fn(node) === true
.
(Not to be confused with wrapper.filterWhere()
, which only looks at "the nodes of the current wrapper", which means direct children from what I can tell)
I whipped up this utility for my current project:
const findWithStyles = (wrapper, name) => {
// Only matches if there are no letters on either side
// i.e.: Button, Styled(WithStyles(ForwardRef(Button)))
// not: MyButton, Buttons
const matchExp = RegExp(`(?<![a-zA-Z])${name}(?![a-zA-Z])`);
return wrapper.findWhere((node) => {
const nodeName = node.name();
// The extra check here is for raw HTML text, for which .name() is null
return nodeName && nodeName.match(matchExp);
});
// Or, if your environment supports optional chaining (a?.b?.c):
// return wrapper.findWhere(node => node.name()?.match(matchExp));
};
const buttons = findWithStyles(wrapper, 'Button');
回答2:
How i have done testing like this, with components that are wrapped in HOCs, is that i export both the wrapped component, and the non-wrapped component.
So, i have
export class MyComponent extends React.Component {
// All the code
}
export default withStyles(MyComponent);
So in my tests, i import the non-wrapped component with
import {MyComponent} from './MyComponent';
And in my code i import the default export
import MyComponent from './MyComponent';
来源:https://stackoverflow.com/questions/54630839/ignore-hoc-when-testing-react-components