When run test, TypeError: Cannot destructure property 'travelDatas' of '(0 , _GetTravelDatas.getTravelDatas)(...)' as it is undefined

When run test, TypeError: Cannot destructure property 'travelDatas' of '(0 , _GetTravelDatas.getTravelDatas)(...)' as it is undefined

当我 运行 测试时,它显示 TypeError: Cannot destructure 属性 'travelDatas' of '(0 , _GetTravelDatas.getTravelDatas)(... )' 因为它是未定义的。

如截图所示:unit test

没有任何控制台错误或警告。

谁能帮忙

travelListTest.spec.js

import { mount, shallowMount } from '@vue/test-utils'
import TravelList from '../../src/components/TravelList.vue'
import { getTravelDatas } from '../../src/composables/GetTravelDatas'
import ElementPlus from 'element-plus'

const wrapper = shallowMount(TravelList, {
  global: {
      plugins: [ElementPlus]
  }
})

jest.mock('../../src/composables/GetTravelDatas')

describe('TravelList Test', () => {
      test('click more will call GoToTravelDetailPage', () => {
        wrapper.vm.GoToTravelDetailPage = jest.fn()
        console.log(wrapper.html())
        wrapper.find('.el-button').trigger('click')
        expect(wrapper.vm.GoToTravelDetailPage).toHaveBeenCalled()
      })
})

TravelList.vue

.....
<script>
import { ref } from '@vue/reactivity';
import { useRouter } from "vue-router";
import { getTravelDatas } from '../composables/GetTravelDatas'
export default {
  name: 'TravelList',
  setup() {
    
    const { travelDatas } = getTravelDatas();
    const router = useRouter();

    function GoToTravelDetailPage(acctractionId) {
      router.push({ path: `/travelDetail/${acctractionId}` })
    }

    
    return { travelDatas, GoToTravelDetailPage };
  },
};
</script>

GetTravelDatas.js

import axios from "axios";
import { ref } from '@vue/runtime-core';

export function getTravelDatas() {
    const travelDatas = ref([])
        axios.get('https://localhost:5001/MyTravel/GetTravelData')
        .then((response) => {
        if (!response.data.success) {
            alert(response.data.errorMessage)
        }else{
            travelDatas.value = response.data.travelDetail
        }
        }).catch((error) => {
        alert('Unexpected Error: ', error.message)
        console.log(error)
        });
    return { travelDatas }
}

您正在使用自动模拟版本模拟 GetTravelDatas 模块,方法是调用:

jest.mock('../../src/composables/GetTravelDatas')

这意味着从该模块导出的所有方法都将被模拟(该方法的真实代码将不会被调用)并且模拟版本将 return undefined 调用时。

在您正在测试的代码中,您有:

const { travelDatas } = getTravelDatas();

undefined 读取 travelDatas 属性 导致您看到的错误。

您应该模拟 getTravelDatas 方法,以便它 return 提供适当的数据。例如,returning 一个空数组看起来像:

getTravelDatas.mockReturnValue([]);