【问题标题】:Testing Vuejs and TypeScript with Jest causes an error "Property 'xxx' does not exist on type 'CombinedVueInstance'用 Jest 测试 Vuejs 和 TypeScript 会导致错误“Property 'xxx' does not exist on type 'CombinedVueInstance'
【发布时间】:2019-06-12 20:53:12
【问题描述】:

我正在尝试为 Vue 组件中的一个函数创建一个基本测试,结果惨遭失败。

main.ts

new Vue({
  render: (h) => h(App),
  router,
  store,
}).$mount('#app')

App.ts

const App = Vue.extend({
    components: { MainContainer },
    data() {
        return {
            msg: 'Test',
        }
    },
    name: 'App',
    template: `<MainContainer />`,
})

export default App

MainContainer.vue

const MainContainer = Vue.extend({
    components: {
        Content,
    },
    methods: {
        sum: (a: number, b: number): number => a + b,
    },
})

export default MainContainer

MainContainer.spec.ts

import { createLocalVue, shallowMount } from '@vue/test-utils'

describe('MainComponent.vue', () => {
    const localVue = createLocalVue()

    test('sum method should add number together', () => {
    const wrapper = shallowMount(MainContainer, { localVue })
    expect(wrapper.vm.sum(1, 2)).toEqual(3)
})

测试失败并出现错误

Property 'sum' does not exist on type 'CombinedVueInstance<Vue, object, object, object, Record<never, any>>'.

如果我尝试从 App.ts 测试 data.msg,我会看到相同的行为。我会很感激任何帮助。谢谢

【问题讨论】:

    标签: typescript vue.js jestjs vue-test-utils


    【解决方案1】:

    您必须指定 wrapper.vm 的类型

    一个可行的解决方案是为 any 指定类型:

    expect((wrapper.vm as any).sum(1, 2)).toEqual(3)
    

    【讨论】:

      猜你喜欢
      • 2019-03-11
      • 2020-10-18
      • 2019-05-05
      • 1970-01-01
      • 2023-01-31
      • 2022-11-17
      • 1970-01-01
      • 2021-01-29
      • 1970-01-01
      相关资源
      最近更新 更多