vuejs / vue-test-utils-typescript-example

Example project using TypeScript, Jest + vue-test-utils together
61 stars 31 forks source link

jest in vue-cli4 with typescript #7

Closed kunfan96 closed 2 years ago

kunfan96 commented 4 years ago

when i want to test a vue components in components.ecpect.ts

import About from '@/components/About.vue'
import { shallowMount } from '@vue/test-utils'

describe('测试事件', () => {
  test('测试事件1', () => {
    const wrapper = shallowMount(About)
    console.log(wrapper.vm)
    wrapper.vm.toggleShow()
    // 执行组件事件
    expect(wrapper.element.style.display).toBe('none')
  })
})

it reports

Test suite failed to run

    TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):

    src/components/__tests__/About.spec.ts:7:16 - error TS2339: Property 'toggleShow' does not exist on type 'CombinedVueInstance<Vue, object, object, object, Record<never, any>>'.
cmauf commented 2 years ago

Problem is that ts-jest uses the Vue prototype, not the instance. In order to avoid the error, use (wrapper.vm as any).toggleShow() instead of wrapper.vm.showToggle() (see this issue for reference)