我尝试改编 Vue unit testing guide ,但卡在了第一个障碍。 Property 'created' does not exist on type 'VueConstructor<Vue>'
.
这是我的测试,只是为了验证我的组件实际上有 created
钩子(Hook):
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
是一个对象,而不是一个函数;你想要的是测试它是否存在。
关于javascript - 使用 Vue、Typescript 和 Karma 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48809244/