我对单元测试Map组件有疑问。
我的班级组成部分:
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和酶进行单元测试
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:无法读取null的属性“ _layerAdd”
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",
答案 0 :(得分:4)
我在传单的github上看到了一堆相关问题。维护者似乎对框架有些反对。 查看https://react-leaflet.js.org/,它应该可以更好地与react配合使用。