模拟子组件的公共方法

时间:2019-02-28 15:06:23

标签: javascript reactjs typescript jestjs enzyme

在一个Jest测试中,我想模拟用ref调用的子组件的特定功能。例如,类似:

const mockedFn = jest.fn();
Child.prototype.functionToMock = mockedFn;
const wrapper = mount(<Parent/>);
wrapper.find(Button).simulate("click");
expect(mockedFn).toBeCalled(); 

父组件的外观类似于:

class Parent extends React.Component {
    private child: RefObject<Canvas> = React.createRef();
    ...
    render() {
        ...
        <Button onClick={this.onButtonClick}/>
        <Child ref={this.child}/>
    }

    private onButtonClick = () => {
        ...
        this.child.current.functionToMock();
    }
}

和子组件看起来像:

class Child extends React.Component {
    ...

    public functionToMock = () => {
        ...
    }
}

我无法模拟整个Child组件,因为还有其他测试取决于Child中包含的某些功能。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

想出后代:

const mockedFn = jest.fn();
const wrapper = mount(<Parent/>);
wrapper.update();
const child = wrapper.find(Child).instance() as Child;
child.functionToMock = mockedFn;
wrapper.find(Button).simulate("click");
expect(mockedFn).toBeCalled();