vue.js - 开 Jest 测试正在从 Vue 观察器调用函数

标签 vue.js testing mocking jestjs

这是我的组件的简化版本:

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 map 进行处理。到目前为止,这是我的 Jest 测试:

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

最佳答案

你试过吗?

it('should react to geoJson changes', async () => {
wrapper.setData({ geoJson: mockGeoJSON });

await wrapper.vm.$nextTick()

expect(hdnMap.fitMap).toHaveBeenCalled();
expect(hdnMap.addGeoJson).toHaveBeenCalled();
});

关于vue.js - 开 Jest 测试正在从 Vue 观察器调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58857214/

相关文章:

java - 有没有不适合 java/scala 的类似 dbunit 的框架?

python - 检查 python 列表是否遵循特定的重复模式

ios - 如何创建在触发功能时通过的测试?

perl mocking 有没有办法模拟 $?

javascript - 在 <i18n> 标签中延迟加载翻译文件

vue.js - Vue - 如何使用 404 响应代码创建 404 错误页面

iphone - 在哪里可以找到带有示例数据的 iPhone 通讯录?

unit-testing - 如果我使用 Mockito,我什至需要 Guice 吗?

vue.js - Vue CLI 为生产环境进行了缩减,但如何缩短属性和其他定义呢?

javascript - Vue.js 不渲染组件