我有一个呈现第三方组件的组件。渲染时,它将组件的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,
}));
我该如何正确地模拟它?