reactjs - React 单元测试传单

标签 reactjs unit-testing leaflet jestjs enzyme

我在单元测试 map 组件时遇到问题。

我的类(class)组件:

componentDidMount() {
    const { zoom, data, center } = this.props;
    const { activeButton } = this.state;
    if (data[activeButton] != null) {
      this.map = map('map', {
        center: data[activeButton].points ? data[activeButton].points[0] : center,
        zoom,
        layers: [tileLayer(...SETTINGS.mapTileLayer)],
      });
      if (data[activeButton].points != null) {
        this.addPolyline(data[activeButton].points);
      }
    }
  }

  addPolyline = (points: Points) => {
    if (this.polyline != null) {
      this.map.removeLayer(this.polyline);
      this.map.removeLayer(this.marker.start);
      this.map.removeLayer(this.marker.stop);
    }

    if (points != null && points[0] != null) {
      this.polyline = new Polyline(points, SETTINGS.polyline);

      this.marker.start = new Marker(points[0]);
      this.marker.stop = new Marker(points[points.length - 1]);

      this.polyline.addTo(this.map);
      this.marker.start.addTo(this.map);
      this.marker.stop.addTo(this.map);

      this.map.panTo(points[0]);
    }
  };

使用 Jest 和 Enzyme 进行单元测试

function getComponent(mockData) {
  return <Map data={mockData} />;
}

const mockData = [
  { id: 0, name: '1', distance: '1', points: [[0, 0], [1, 1]] },
  { id: 1, name: '2', distance: '2', points: [[0, 0], [1, 1]] },
];

describe('LastActivity component', () => {  
  it('button click', () => {
    const wrapper = mount(getComponent(mockData), { attachTo: document.body });

...etc...
});

通过这个测试我得到了

TypeError: Cannot read property '_layerAdd' of null

this.polyline.addTo(this.map);

当我注释掉这一行时

this.polyline.addTo(this.map);

一切正常,测试通过

package.json:

"enzyme-adapter-react-16": "1.2.0",
"enzyme": "3.4.4",
"react": "16.4.2",
"react-dom": "16.4.2",
"leaflet": "1.3.4",
"jest": "23.5.0",
"jest-cli": "23.5.0",

最佳答案

我在传单的 github 上看到了一堆相关问题。维护者似乎对框架有一些反对。 查看https://react-leaflet.js.org/这应该与 React 配合使用效果更好。

关于reactjs - React 单元测试传单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52192422/

相关文章:

javascript - 如何在 recharts 中按 y 轴上的固定数量分隔值

css - 单击时禁用或渲染复选框标签背景突出显示为透明

c# - 如何为 IGrouping 设置 NUnit 模拟对象

ios - 在每个测试用例之后将单例实例重置为 nil

ruby Test::Unit 命令行选项?

typescript - 如何为 Leaflet 插件添加 Typescript 定义

javascript - 使用 Leaflet 和 AngularJS 的热图

javascript - 使用输入类型 'file' 在浏览器存储中存储图像 - Reactjs

leaflet - 我如何在传单 map 中显示 geojson FeatureCollection?

javascript - 如何在用于状态的对象中删除和添加数组元素?