使用 Vue 组件的 mocha 进行单元测试时,base class 中的方法不存在

Method in base class does not exist during unit testing with mocha of Vue component

当我在 Vue 中有一个从基础 class 扩展的组件时,它在浏览器中按预期工作 运行 时间。但是当使用 mocha 进行单元测试时,base class 上的方法消失了。在下面的简单示例中,这会导致错误 TypeError: this.methodInBaseClass is not a function。但是在 运行 它工作的时候,然后显示消息 Some other data,正如我所期望的那样。

出了什么问题?更重要的是,如何修复它?

考虑这个简单的 Vue 组件:

<template>
    <div>{{ myData }}</div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import BaseClass from '@/components/BaseClass.vue';

@Component
export default class HelloWorld extends BaseClass {
    @Prop() private msg!: string;

    private created(): void {
        this.methodInBaseClass();
    }
}
</script>

和基础class

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
export default class BaseClass extends Vue {
    protected myData: string = 'Some data';

    protected methodInBaseClass(): void {
        this.myData = 'Some other data';
    }
}
</script>

和单元测试

import { expect } from 'chai';
import { shallowMount } from '@vue/test-utils';
import HelloWorld from '@/components/HelloWorld.vue';

describe('HelloWorld.vue', () => {
    it('Data is mutated', () => {
        const wrapper = shallowMount(HelloWorld);
        expect(wrapper.html()).to.include('Some other data');
    });
});

您需要将 Component 装饰器添加到基础 class 以便方法 methodInBaseClass 可以声明为 vue-object 方法:

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
@Component
export default class BaseClass extends Vue {
    protected myData: string = 'Some data';

    protected methodInBaseClass(): void {
        this.myData = 'Some other data';
    }
}
</script>

如果您想在抽象 class 上使用 Component 装饰器,您可以使用以下技巧。

创建一个新的 AbstractComponent 装饰器:

import { Component } from 'vue-property-decorator';
export default function AbstractComponent(v: any) {
    return Component(v);
}

您将能够在抽象 class 上使用 AbstractComponent 装饰器,并获得与 Component 装饰器相同的功能。