对使用依赖项的vue组件进行单元测试

时间:2020-06-03 10:08:50

标签: typescript unit-testing vue.js syncfusion ej2-syncfusion

我正在尝试测试使用外部依赖项的SiWizard组件。它从syncfusion库中导入模块。

SiWizard.vue导入

import SiFooter from "@/components/subComponents/SiFooter.vue";
import { Prop, Component, Vue } from "vue-property-decorator";
import { TabPlugin, TabComponent, SelectingEventArgs } from "@syncfusion/ej2-vue-navigations";
import { VNode } from "vue";

Vue.use(TabPlugin);

这就是我使用vue js test utils和jest进行测试的样子。为简单起见,我的测试用例应通过并配置一个道具。

siWizard.spec.ts

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

let wrapper: Wrapper<SiWizard & { [key: string]: any }>;

describe("testing SiWizard", () => {
  test("Test add mode", () => {
    wrapper = shallowMount(SiWizard, {
      propsData: {
        mode: "add"
      }
    });

    expect(true).toBe(true)
  });

运行siWizard.spec.ts时,出现奇怪的错误。 Error without mocking, test still passes

我的猜测是测试环境中的属性无法访问SiWizard组件中使用的依赖项属性。因此,我必须使用Jest模拟TabPlugin。因此,我尝试使用jest.mock模拟依赖关系。

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

// import { TabPlugin } from "@syncfusion/ej2-vue-navigations";

jest.mock("../../node_modules/@syncfusion/ej2-navigations" , () => { jest.fn() });

let wrapper: Wrapper<SiWizard & { [key: string]: any }>;

describe("testing SiWizard", () => {
  test("Test add mode", () => {
    wrapper = shallowMount(SiWizard, {
      propsData: {
        mode: "add"
      }
    });

    expect(true).toBe(true)
  });

导致测试失败并给出以下错误Error and failing test

我不确定我是否需要模拟任何东西,因为我的第一个测试仍然通过了,但这只会给我错误。谁能告诉我我是否正确嘲笑还是需要做其他事情?

2 个答案:

答案 0 :(得分:0)

在您的测试文件顶部添加: jest.mock("../../node_modules/@syncfusion/ej2-navigations")

答案 1 :(得分:-1)

很抱歉延迟回复您。

我们已检查了您报告的问题,并能够在最后将其复制。我们正在检查解决此问题的方法,并让您了解其详细信息。在此之前,我们要求您在Mocha中使用业力单元测试,然后您可以从下面的链接下载示例项目。

示例:https://www.syncfusion.com/downloads/support/directtrac/general/ze/sync-vue-ts-karma-1195414389

代码段:

NPM软件包:

npm install --save-dev karma karma-chrome-launcher karma-mocha karma-sourcemap-loader karma-spec-reporter karma-webpack mocha

./ tests / unit / example.spec.ts

import { expect } from 'chai'
import Vue from "vue";
import HelloWorld from '@/components/HelloWorld.vue'

describe('HelloWorld.vue', () => {
  let vm: any;
  let dropdown: any;
  beforeEach(() => {
    vm = new Vue({
      el: document.createElement("div"),
      render(h) {
        return h(HelloWorld);
      },
    });
    dropdown = vm.$children[0].$refs.dropdownElement;
  });

  afterEach(() => {
    vm.$destroy();
  });


  it('checking default value of dropdown', () => {
    expect(dropdown.value).to.equal('Badminton');
  })

  it('changing the value of dropdown', () => {
    let vm1: any = vm.$children[0].$data;
    vm1.selectedValue = 'Cricket';
    Vue.set(vm1, 'selectedValue' , 'Cricket');
    Vue.nextTick().then(()=>{
      expect(dropdown.value).to.equal('Cricket');
    });
  })

})

如果您需要进一步的帮助,请与我们联系。