使用Vue,Typescript和Karma进行单元测试

时间:2018-02-15 14:09:54

标签: javascript typescript vue.js karma-runner

我试图调整Vue unit testing guide,但在第一道障碍时陷入困境。 Property 'created' does not exist on type 'VueConstructor<Vue>'

这是我的测试,只是为了验证我的组件确实有一个created钩子:

import {assert} from 'chai';
import MyComponent from '../src/components/MyComponent.vue';

it('has a created hook', function() {
    assert.equal(typeof MyComponent.created, 'function');
});

这是我正在测试的组件MyComponent.vue

<template>
</template>

<script lang="ts">
export default Vue.extend({
    created() {
        console.log("bye");
    }
});
</script>

此测试现在应该通过。但是,我从Typescript编译器中得到一个错误。

$ karma start --single-run
15 02 2018 14:06:17.345:INFO [compiler.karma-typescript]: Compiling project using Typescript 2.6.2
15 02 2018 14:06:18.905:ERROR [compiler.karma-typescript]: test/vue_test.ts(5,37): error TS2339: Property 'created' does not exist on type 'VueConstructor<Vue>'.

我正在使用文件vue-shims.d.ts,就是这样:

declare module "*.vue" {
    import Vue from "vue";
    export default Vue;
}

2 个答案:

答案 0 :(得分:1)

使用double f(double x) { exp = pow(-x, 2); double result = x - exp; return x; }; 时,导出组件中声明的默认属性将保存在options属性中。

因此,这可以测试你想要的东西:

Vue.extend

这种方式更好,因为expect(MyComponent.options.created).to.exist 是一个对象,而不是一个函数;而你想要的是测试它是否存在。

答案 1 :(得分:0)

如果您想创建一个在下面需要的组件上使用的功能

export default Vue.extend({     方法:created =&gt; (){         的console.log(&#34;再见&#34);     } });

然后像下面那样测试

it('has a created hook', function() {
    assert.equal(typeof (new MyComponent()).created, 'function');
});

如果您想将其作为组件选项,则需要使用原始模板并将测试用作

it('has a created hook', function() {
    assert.equal(typeof MyComponent.options.created, 'function');
});
相关问题