reactjs - 如何使用 Enzyme 在 react-leaflet 自定义子组件中测试地图参考?
问题描述
我通过扩展 MapControl 在 react-leaflet 中创建了一个自定义组件。该组件不返回任何内容,而是map
通过 props 向它所引用的对象添加一些内容。
自定义子组件
import { MapControl, withLeaflet } from "react-leaflet";
import * as L from "leaflet";
class Dashboard extends MapControl<any, any> {
public createLeafletElement(props: any) {}
public addDashboard() {
const dashboard = L.control({ position: "topright" });
dashboard.onAdd = function() {
this._div = L.DomUtil.create("div", "dashboard");
this._div.setAttribute("data-test", "component-dashboard");
return this._div;
};
const { map } = this.props.leaflet;
dashboard.addTo(map);
}
componentDidMount() {
this.addDashboard();
}
render() {
return null;
}
}
export default withLeaflet(Dashboard);
父/地图组件
import React from "react";
import { Map, TileLayer } from "react-leaflet";
import Dashboard from "./Dashboard";
class MapContainer extends React.Component<any> {
public constructor(props: any) {
super(props);
}
render() {
return (
<div data-test="component-map">
<Map
center={this.props.center}
zoomSnap={this.props.zoomSnap}
zoom={this.props.zoom}
style={this.props.style}
>
<TileLayer
url={this.props.url}
attribution={this.props.attribution}
/>
<Dashboard />
</Map>
</div>
);
}
}
export default MapContainer;
在测试子组件 Dashboard 时,如何初始化地图?(然后检查它是否包含仪表板)我正在使用 Jest 和 Enzyme
解决方案
对于Jest,以下示例演示了如何:
- 创建
react-leaflet
Map
组件实例 - 确保实例化自定义控件(
Dashboard
在您的情况下)
例子
import React from "react";
import ReactDOM from "react-dom";
import { renderIntoDocument } from "react-dom/test-utils";
import { Map, TileLayer } from "react-leaflet";
import Dashboard from "./Dashboard";
it("Control test", () => {
class TestComponent extends React.Component {
constructor() {
super();
this.controlRef = React.createRef();
}
getControl() {
return this.controlRef.current.leafletElement;
}
render() {
return (
<Map center={[0,0]} zoom={10}>
<Dashboard ref={this.controlRef} />
</Map>
);
}
}
const component = renderIntoDocument(<TestComponent />);
const control = component.getControl();
expect(control).not.toBeNull();
});
推荐阅读
- python - selenium python page down - 未知错误:net::ERR_NAME_NOT_RESOLVED
- java - 为什么在这种情况下会发生拆箱?
- c - 如何优化程序的性能С
- python - 构建一个 Discord 机器人来 DM 特定用户 - AttributeError: 'NoneType' object has no attribute 'send'
- flutter - 如何在 Flutter 中更改 Scrollbar 小部件的颜色?
- oracle - 如何知道触发器中 :new 的类型?
- javascript - 我的代码不能绘制任何东西而不是显示白色画布
- ios - 如何将 ContextMenu 与 NavigationLink 一起使用?
- python - 你如何改变 ttk.Radiobutton 圆圈/钻石?
- javascript - 当我将对象的值从文本更改为数字时,在 javascript 中出现错误 nan