首页 > 解决方案 > 如何在酶/反应中获取子组件的文本()

问题描述

我有一个childComponent有文字的。

我写了一个test正在检查该文本的内容。该测试通过了,直到我做了两个显着的改变。我需要保留这些更改,并让测试通过。

  1. 该组件已被重构以使用forwardRef
  2. 我试图测试文本的 childComponent 被定义为 parentComponent 的属性,例如parentComponent.childComponent = childComponent

当 parentComponent 不使用时,测试工作正常forwardRef

childComponent当我在控制台中打印父级的 html() 时,我可以看到文本。

HTML:

  <div class="parentComponent">
    <div class="childComponent">
      childText
    </div>
  </div>

父组件:

class SelectRef extends PureComponent {
   /// component code here
} 
// Bottom of parentComponent
const Select = forwardRef((props, ref) => <SelectRef {...props} innerRef={ref} />);
Select.displayName = "Select";
Select.Option = Option;

export default Select;

我试过了:

expect(component.dive().text()).to.contain("text");
expect(component.shallow().text()).to.contain("text");
expect(component.prop('children')).to.contain("text");

使用 Enyzme / React 在组件中获取 childComponent 文本的其他方法是什么?

标签: reactjstestingtextenzyme

解决方案


这是使用forwardRef时执行此操作的一种方法:

我在酶测试中有一个辅助函数,允许您访问forwardRef包装器中的函数:

const getComp = (comp, className = "default-class") =>
  comp
    .find("ComponentRef")
    .dive()
    .find(className);

示例测试:

  it("should render the place holder text", () => {
      const component = shallow(
        <Component placeholderText="Select an option" selectName="test"/>
      );

      const comp = getComp(component)
      expect(comp.text()).to.contain("inner text of component");
  }); 

推荐阅读