簡體   English   中英

使用 Vue、Typescript 和 Karma 進行單元測試

[英]Unit testing with Vue, Typescript and Karma

我嘗試修改Vue 單元測試指南,但在第一關卡住了。 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;
}

使用Vue.extend時,導出組件中聲明的默認屬性保存在options屬性中。

因此,這可以測試你想要什么:

expect(MyComponent.options.created).to.exist

這種方式更好,因為options.created是一個對象,而不是一個函數; 你想要的是測試它是否存在。

如果您想創建一個要在組件上使用的函數,您需要在下面

export default Vue.extend({ methods: created => () { console.log("bye"); } });

然后像下面這樣測試它

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

如果您希望它作為組件選項,那么您需要使用原始模板並將測試用作

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM