【问题标题】:Unit testing with Vue, Typescript and Karma使用 Vue、Typescript 和 Karma 进行单元测试
【发布时间】:2018-07-26 07:52:32
【问题描述】:

我尝试调整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;
}

【问题讨论】:

  • 你可以试试assert.equal(typeof MyComponent().created, 'function');Vue.extend 返回一个新的构造函数而不是一个对象
  • @TarunLalwani 这给了Value of type 'VueConstructor&lt;Vue&gt;' is not callable。使用typeof (new MyComponent()).created 得到Property 'created' does not exist on type 'CombinedVueInstance&lt;Vue, object, object, object, Record&lt;never, any&gt;&gt;'
  • 看来您在这里错误地使用了Vue.extend。你需要像Vue.extend ({ methods: { created: () =&gt; "created" } } )一样使用它

标签: javascript typescript vue.js karma-runner


【解决方案1】:

导出组件中声明的默认属性在使用Vue.extend时保存在options属性中。

因此,这可以测试你想要什么:

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

这样更好,因为options.created 是一个对象,而不是一个函数;而你想要的是测试它是否存在。

【讨论】:

  • 任何引用 MyComponent.options 的尝试都会导致类型错误 Property 'options' does not exist on type 'VueConstructor&lt;Vue&gt;'
  • 这很有趣,在您的测试中包含类似console.log('MyComponent Properties', Object.getOwnPropertyNames(MyComponent)) 的内容以确保。就此而言,您能否包含所有代码的最小示例?查看minimum, complete and verifiable example。包括文件夹结构。
  • 看起来MyComponent 在测试上下文中是未定义的,即使在成功导入之后也是如此。但是在被测小应用程序中导入和使用MyComponent 工作正常。我真的不明白这怎么可能。我可能需要在几天后调查并返回这个问题,因为它看起来可能是配置问题而不是代码问题。
  • 很有趣,如果你仍然可以包含 mcve,也许我仍然可以找到问题的根源。
  • 这里是代码,尽可能地最小化。我猜karma-typescript 需要配置为运行 vue webpack 加载器,以便 vue 组件的导入可以正常工作。但是现在没有时间测试它。 github.com/amoe/mcve-48809244
【解决方案2】:

如果你想创建一个在组件上使用的函数,你需要在下面

导出默认 Vue.extend({ 方法:创建=>(){ console.log("再见"); } });

然后像下面这样测试它

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');
});

【讨论】:

  • 第一个不提供相同的语义,created 钩子与created 方法不同。第二个想法很好,但给了我错误Property 'options' does not exist on type 'VueConstructor&lt;Vue&gt;'
猜你喜欢
  • 2015-09-16
  • 1970-01-01
  • 2017-01-03
  • 2019-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-01
  • 1970-01-01
相关资源
最近更新 更多