【发布时间】:2018-09-05 19:45:46
【问题描述】:
我在单元测试 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 和 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: 无法读取 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",
【问题讨论】:
-
您是否尝试过查看您在 chrome 控制台上传递的内容?可能是您没有向 this.polyline 传递任何内容?在他们的文档中,Polyline 似乎没有这种方法可以测试?
标签: reactjs unit-testing leaflet jestjs enzyme