如何在玩笑中模拟远程模块(远程React组件)?

问题描述 投票:0回答:1

我有一个 React 组件,我正在使用 Jest 和 React 测试库为其编写测试用例。

MyComponent.tsx:

import RemoteComponent from '@remote-module/remote-component'

function MyComponent = ({triggerLog}) => {
  const errorHandler = (error) => {
    triggerLog(error)
  }
 
  return (
      <RemoteComponent
        errorLogCallback={errorHandler}
      />
  )
}

export default MyComponent

请告诉我如何模拟 RemoteComponent,因为我想在 Jest 中覆盖 errorHandler 方法。

reactjs jestjs react-testing-library
1个回答
0
投票

你可以这样嘲笑它

// this is needed as jest hoists the `.mock` calls on top
// and also variables prefixed with `mock`
const mockUseEffect = useEffect;

jest.mock(
  '@remote-module/remote-component',
  () =>
    ({ errorLogCallback }: { errorLogCallback: (error: Error) => void }) => {
      mockUseEffect(() => {
        errorLogCallback(new Error('testing error'));
      });
      return null;
    },
);

您可以预期在组件渲染后会调用

triggerLog

© www.soinside.com 2019 - 2024. All rights reserved.