首页 > 解决方案 > 如何模拟一个带有“ref”的组件?

问题描述

我有一些代码,例如:

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

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


    <GoogleMap ref={zoomToBounds}>
        ...
    </GoogleMap>
}

GoogleMap并且在我测试时试图用玩笑来嘲笑GoogleMapContainer

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

但是,我收到如下错误:

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

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

我如何绕过ref错误?

标签: reactjsjestjs

解决方案


在回答我自己的问题。

如果你的名字以mock. 然后你可以在 mock 之后 require 包含类,保证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;

推荐阅读