开玩笑测试正在从 Vue watcher 调用函数

Posted

技术标签:

【中文标题】开玩笑测试正在从 Vue watcher 调用函数【英文标题】:Jest test that functions are being called from Vue watcher 【发布时间】:2020-03-10 10:29:59 【问题描述】:

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

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()。我想模拟这些调用,因为这些函数对我不想测试的谷歌地图做了一些事情。到目前为止,这是我的玩笑测试:

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

【问题讨论】:

曾经解决过这个问题吗?在 Jest 中测试组件时,我遇到了观察者方法没有被触发的问题。 【参考方案1】:

你试过了吗?

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

await wrapper.vm.$nextTick()

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

【讨论】:

不幸的是我得到了同样的结果

以上是关于开玩笑测试正在从 Vue watcher 调用函数的主要内容,如果未能解决你的问题,请参考以下文章

如何模拟 axios API 调用?开玩笑

开玩笑的测试在调用模拟的 firebase 函数之前完成,因此失败

如何测试从 VueX 监视计算属性的 Vue watcher?

vue之watch实现原理

在“if”语句中没有调用模拟函数 - 用玩笑和酶反应应用程序测试?

不能用玩笑模拟模块,并测试函数调用