reactjs - 如何在酶/反应中获取子组件的文本()
问题描述
我有一个childComponent
有文字的。
我写了一个test
正在检查该文本的内容。该测试通过了,直到我做了两个显着的改变。我需要保留这些更改,并让测试通过。
- 该组件已被重构以使用
forwardRef
- 我试图测试文本的 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 文本的其他方法是什么?
解决方案
这是使用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");
});
推荐阅读
- bash - 通过 Docker CLI 过滤掉多个图像
- android-studio - 我们可以在导航活动中自定义默认操作栏(内置)吗
- python - 如何使用正则表达式删除python中某个字符串的前导和尾随非字母数字字符?
- javascript - 为什么我的 Javascript 代码中的元素在达到 200 像素后不会停止移动?
- vue.js - 如何在注销时清除所有 Vuex 4 状态?
- sails.js - 在sails JS中链接控制器动作 - 动作2格式
- kframework - Pi 演算中的变量替换错误
- javascript - 如何为图片库的标题创建搜索过滤器?
- json - 哪种日志记录时间戳格式?
- cassandra - 最后在 cassandra 中记录每组