在Jest中模拟回调ref

时间:2020-02-10 02:53:52

标签: reactjs jestjs react-testing-library

我有一个呈现第三方组件的组件。渲染时,它将组件的ref本地存储在localApi中。单击按钮后,它将调用exportData函数,该函数将在回调中返回一些数据。

const MyComponent = () => {
    let localApi = React.useRef() as any;

    const submit = () => {
        localApi.exportData((data) => {
            // do something with data
        })
    }

    return (
        <>
            <ThirdParty ref={(api) => localApi = api} fullVersion={true}/>
            <button onSubmit={submit}>Submit</button>
        </>
    )
}

我面临的问题是在Jest中模拟ThirdParty组件的ref。由于我的模拟无法正常工作,因此在模拟单击时,按钮会引发exportData is not defined错误。我已经尝试了以下方法,但无济于事:

jest.mock("third-party", () => ({
    default: (props: any) => {
        // tslint:disable-next-line: no-shadowed-variable
        const React = require("react");

        console.log(props); // this only returns the `fullVersion = true` when 

        const MockThirdParty: React.FC = () => {
            const exportData = (callBack) => {
                callBack("Mock data");
            }

            return <div>Third Party Component</div>;
        }

        return <MockThirdParty/>;
    },
    __esModule: true,
}));

我该如何正确地模拟它?

0 个答案:

没有答案
相关问题