我没有编写测试的丰富经验,所以我不确定如何最好地解决这个问题,但是我有一个react应用,其父组件是呈现的MapBox实例。我想测试组件componentdidmount
中正在进行的所有操作。
它看起来像这样:
componentDidMount = () => {
const containerEl = this.mapContainer;
if(containerEl && containerEl.current) {
mapboxGl.accessToken = ACCESS_TOKEN;
this.popupContainer = document.createElement('div')
const map = new mapboxGl.Map({
container: containerEl.current,
style: style,
center: [-122.396449, 37.791256],
zoom: 15
});
this.setState({ map });
map.on('click', 'poi-label', (e) => {
let features = map.queryRenderedFeatures(e.point, {
layers: ['poi-label']
});
let feature = features[0];
const popup = new mapboxGl.Marker(this.popupContainer, { offset: [0, -75] })
.setLngLat(feature.geometry.coordinates)
.addTo(map);
this.popupElement = popup._element
this.popupName = feature.properties.name
let favoritePOI = this.state.favoritePOI
map.flyTo({ center: e.lngLat});
this.setState({ showPopup: true, popupInstanceEl: this.popupElement, currentName: this.popupName });
this.setPopUp(features, this.addFavorite, this.removeFavorite, this.closeMarker, favoritePOI)
});
}
}
到目前为止,我的设置测试如下:
jest.mock('mapbox-gl', () => ({
Map: jest.fn()
}))
describe('MapView', () => {
let wrapper;
beforeEach(() => {
mapboxGl.Map.mockReset();
wrapper = mount(<MapView />)
});
it('renders', () => {
expect(mountToJson(wrapper)).toMatchSnapshot();
})
it('initializes mapbox gl', () => {
expect(mapboxGl.Map).toHaveBeenCalledTimes(1)
})
it('initializes mapbox gl marker', () => {
expect(mapboxGl.Marker).toHaveBeenCalledTimes(1)
})
})
我遇到几个错误,其中最突出的是Error: Uncaught [TypeError: map.on is not a function]
以及 `expect(value).toMatchSnapshot()
Received value does not match stored snapshot "MapView renders 1".
- Snapshot
+ Received
- <MapView>
- <div
- className="map-container"
- />
- </MapView>
+ null`
任何线索,这是怎么回事,我该如何解决?