Ignore HOC when testing React Components

五迷三道 提交于 2021-01-29 08:20:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!