简体   繁体   English

方法在单元测试中不可用

[英]Method isn't available in unit test

I created new project in VueJS with TypeScript.我使用 TypeScript 在 VueJS 中创建了新项目。

My component with methods to test:我的组件具有测试方法:

<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>

Test:测试:

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')
  })
});

and now I would like do test but methods setSlide, setSliding isn't available in wrapper :(现在我想做测试,但是方法 setSlide、setSliding 在包装器中不可用:(

Try this:尝试这个:

import YourComponentHere from "@/components/YourComponentHere";
import { shallowMount, Wrapper } from "@vue/test-utils";

describe("test", () => {
  const wrapper: Wrapper<YourComponentHere & { [key: string]: any }>;
  it("does something", () => {
    expect(wrapper.vm.someThingWhatever).toBe(true);
  });
});

The advantage here is that you don't need to cast wrapper.vm to any everytime you use wrapper.vm这里的优点是每次使用wrapper.vm都不需要将wrapper.vmany

It seems you have to cast wrapper.vm as any for TypeScript not to complain:似乎您必须将wrapper.vmany才能让 TypeScript 不抱怨:

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

Or at the top of your tests:或者在测试的顶部:

const wrapper: any = shallowMount(Slider);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM