这是我组件的简化版本:
export default {
props: {
geoJson: {
type: Object,
default: () => ({}),
},
},
watch: {
geoJson(geoJsonObj) {
this.addGeoJson(geoJsonObj);
this.fitMap();
},
},
methods: {
/**
* Fit bounds to ALL features shown on map
* @return {void}
*/
fitMap() {
const bounds = new google.maps.LatLngBounds();
this.map.data.forEach(feature => {
feature.getGeometry().forEachLatLng(latlng => {
bounds.extend(latlng);
});
});
this.map.fitBounds(bounds);
},
/**
* Add GeoJSON to map
* @param {Object}
*/
addGeoJson(geoJsonObj) {
this.map.data.addGeoJson(geoJsonObj);
},
},
};
</script>
我要测试观察者在其值更改时正在调用addGeoJson()
和fitMap()
。我想模拟这些调用,因为这些函数可以处理我不想测试的Google Maps。到目前为止,这是我开玩笑的测试:
import { shallowMount } from '@vue/test-utils';
import hdnMap from '../hdnMap.vue';
let wrapper;
jest.mock('../../../../utils/gmap');
const mockGeoJSON = [
{
type: 'Feature',
geometry: {
type: 'LineString',
coordinates: [[102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]],
},
properties: {
prop0: 'value0',
prop1: 0.0,
},
},
];
beforeEach(() => {
wrapper = shallowMount(hdnMap);
});
it('should mount without crashing', () => {
expect(wrapper.isVueInstance()).toBe(true);
});
it('should react to geoJson changes', () => {
wrapper.setData({ geoJson: mockGeoJSON });
expect(hdnMap.fitMap).toHaveBeenCalled();
expect(hdnMap.addGeoJson).toHaveBeenCalled();
});
但是Jest
说我的函数从未被调用:
Expected number of calls: >= 1
Received number of calls: 0
答案 0 :(得分:0)
您尝试过吗?
it('should react to geoJson changes', async () => {
wrapper.setData({ geoJson: mockGeoJSON });
await wrapper.vm.$nextTick()
expect(hdnMap.fitMap).toHaveBeenCalled();
expect(hdnMap.addGeoJson).toHaveBeenCalled();
});