我有一个react"包装"应该包装其子组件的组件。以下是相关部分:
export class Wrapper extends Component {
render(){
return (<div>{ this.props.children }</div>);
}
}
我正在尝试使用jest
来测试渲染的子节点是否确实提供给此包装器。
这是我试过的;
describe('SwapWrapper', () => {
it('contains its child', () => {
const potentialChild = (<AMockedComponent/>);
const wrapper = TestUtils.renderIntoDocument(
<Wrapper>{potentialChild}</Wrapper>
);
const realChild = TestUtils.findRenderedComponentWithType(wrapper, AMockedComponent);
expect(realChild).toBe(potentialChild); // Obviously does not work.
});
});
显然不起作用。 realChild
is a component instance while potentialChild
is a component element
目前,我唯一能做的就是使用属性创建potentialChild
并检查realChild
是否包含此属性。
是否有更有效的方法来检查realChild
是否与已提供的potentialChild
相对应?
答案 0 :(得分:0)
我找到了使用ScrollView的解决方案。
在实例化时,将使用创建的实例回调react元素的ref
属性。
describe('SwapWrapper', () => {
it('contains its child', () => {
const ref = jest.fn();
const potentialChild = (<AMockedComponent ref={ref}/>);
const wrapper = TestUtils.renderIntoDocument(
<Wrapper>{potentialChild}</Wrapper>
);
const realChild = TestUtils.findRenderedComponentWithType(wrapper, AMockedComponent);
expect(ref).toBeCalledWith(realChild);
});
});