测试React组件时忽略HOC [英] Ignore HOC when testing React Components

查看:109
本文介绍了测试React组件时忽略HOC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试一个简单的Material UI选择表单,该表单使用FormControl并随Styles一起导出.我的测试用例非常简单,例如,我想断言我的组件呈现了一个孩子. 我尝试以下断言:

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);

但是,此断言仅因InputLabel包装在 WithStyles AND WithFromControlContext 中而失败(请参见调试输出):

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)>

有什么方法可以忽略掉所有包裹在它周围的HOC组件,来测试InputLabel子项的存在吗?

Is there any way to just test for the existence of the InputLabel child ignoring all the HOC components which are wrapped around it?

推荐答案

除了wrapper.find(),Enzyme还提供

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.

(不要与wrapper.filterWhere()混淆,wrapper.filterWhere()只看当前包装器的节点",这意味着我可以说的是直接子级)

(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');

这篇关于测试React组件时忽略HOC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆