该方法在单元测试中不可用

na5*_*tyk 5 javascript unit-testing typescript vue.js jestjs

我使用 TypeScript 在 VueJS 中创建了新项目。

我的组件具有要测试的方法:

<template>
    <div></div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';

@Component
export default class Slider extends Vue {
  private slide: number = 0;
  private sliding: boolean = false;

  public setSlide(slide: number): void {
    this.slide = slide;
  }

  public setSliding(sliding: boolean): void {
    this.sliding = sliding;
  }

  private onSliderStart(slide: any): void {
    this.setSliding(true);
  }

  private onSlideEnd(slide: any): void {
    this.setSliding(false);
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)

测试:

import { shallowMount } from '@vue/test-utils';
import Slider from '@/components/Header.vue';

describe('Slider', () => {
  const wrapper = shallowMount(Slider);

  it('check Slider is a Vue Instance', () => {
    expect(wrapper.isVueInstance()).toBeTruthy();
  });

  it('setSlide is func', () => {
    expect(typeof wrapper.vm.setSlide).toBe('function')
  })
});
Run Code Online (Sandbox Code Playgroud)

现在我想做测试,但方法 setSlide、setSliding 在包装器中不可用:(

chi*_*t24 3

看来你必须像 TypeScript 一样进行转换wrapper.vmany不会抱怨:

it('setSlide is func', () => {
  expect(typeof (wrapper.vm as any).setSlide).toBe('function')
})
Run Code Online (Sandbox Code Playgroud)

或者在测试的顶部:

const wrapper: any = shallowMount(Slider);
Run Code Online (Sandbox Code Playgroud)

来源: https: //github.com/vuejs/vue-test-utils/issues/255#issuecomment-433312728