假设您有以下两个组件
class Parent ... {
render() {
let child;
if(this.props.children[0].type.IS_CHILD){
this.props.children[0].isInsideParent = true;
child = this.props.children[0];
return <div>{child}</div>
}
return <div>ERROR</div>
}
}
class Child ... {
public static IS_CHILD = true;
render() {
let parent;
if(this.props.isInsideParent)
return <div>OK</div>;
return <div>ERROR</div>
}
}
如果您尝试使用酶进行测试,请按以下步骤进行:
const wrapper1 = shallow(<Parent><Child></Child></Parent>)
const wrapper2 = shallow(<Parent><Child></Child></Parent>).dive();
const wrapper3 = mount(<Parent><Child></Child></Parent>)
它将只与mount
一起工作,因为它是唯一渲染内部组件的(因此是子组件[0])。type被定义为Child类,所以它有一个IS_CHILD属性)。
相反,使用shallow,它会尝试呈现Parent组件,但是当它尝试查看它内部是否有Child元素时,它不会看到它(children[0])。type将等于function ShallowRenderStub(_a))
有没有一种方法可以用酶来测试这种非常特殊的情况?
父级逻辑依赖于呈现特定的子组件。你得到了你自己的答案-你应该使用mount
,因为它呈现子组件。
shallow()和mount()之间的区别在于,shallow()与它们呈现的子组件隔离地测试组件,而mount()更深入地测试组件的子组件。
来源:什么时候应该在酶/反应测试中使用渲染和浅层?