测试反应成分的孩子是否实际上是被提供的孩子,并且开玩笑

时间:2016-06-13 06:45:07

标签: javascript reactjs jestjs

我有一个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相对应?

1 个答案:

答案 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);
    });
});