reactjs - 如何模拟一个带有“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
错误?
解决方案
在回答我自己的问题。
如果你的名字以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;
推荐阅读
- kubernetes - Suse Linuxenterprize server 15虚拟机如何安装kubernetes?
- node.js - 将对象保存到 JSON 文件而不是在读取后在函数中使用它
- c# - 如何在 Flurl 调用上全局设置 HttpMessageHandler 而无需调用 Configure()
- excel - VBA Excel - 如果数组包含一些字符串
- r - R中这行代码的错误可能是什么
- python - 试图避免使用 tkinter 结合 .pack() 和 .grid() 并挣扎。哪个选项更好,为什么?
- regex - 已解决:哪些 RegexExtract 参数可以提取具有不同长度和格式的数字
- azure-powershell - Powershell 帮助比较
- python - X 轴没有像数据框中那样正确显示
- javascript - Discord.js v12 如何将新创建的角色分配给用户?