如何用笑话模拟具有“ref”的组件?

bre*_*son 5 reactjs jestjs

我有一些代码,例如:

import { GoogleMap } from 'react-google-maps';

const GoogleMapContainer = () => {
    const zoomToBounds = React.useCallback(
        (map): void => map && bounds && map.fitBounds(bounds),
        [bounds]
    );


    <GoogleMap ref={zoomToBounds}>
        ...
    </GoogleMap>
}
Run Code Online (Sandbox Code Playgroud)

GoogleMap当我测试时我试图开玩笑GoogleMapContainer

jest.mock('react-google-maps', () => ({
      GoogleMap: (props) => <div>{props.children}</div>,
}));
Run Code Online (Sandbox Code Playgroud)

但是,我收到如下错误:

    Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
Run Code Online (Sandbox Code Playgroud)

我无法使用,forwardRef因为笑话抱怨使用范围之外的函数。如果我尝试为 GoogleMap 创建模拟的基于类的组件,我会得到同样的错误。

我该如何解决该ref错误?

bre*_*son 2

回答我自己的问题。

如果您的名称以 . 开头,您可以在模拟中引用外部变量mock。然后,您可以在模拟之后要求包含类,以保证MockGoogleMap设置外部变量()。

class MockGoogleMap extends Component {
  constructor(props) {
    super(props);
  }
  render(): ReactElement {
    return <div>{this.props.children}</div>;
  }
}

jest.mock('react-google-maps', () => ({
  GoogleMap: MockGoogleMap,
}));
const GoogleMapContainer = require('./GoogleMapContainer').default;
Run Code Online (Sandbox Code Playgroud)