amoe
amoe

Reputation: 4569

Unit testing with Vue, Typescript and Karma

I tried to adapt the Vue unit testing guide, but got stuck at the first hurdle. Property 'created' does not exist on type 'VueConstructor<Vue>'.

Here's my test, just to verify that my component does in fact have a 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');
});

Here's my component under test, MyComponent.vue:

<template>
</template>

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

This test should now pass. However, I get an error from the Typescript compiler.

$ 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>'.

I am using a file vue-shims.d.ts, which is as such:

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

Upvotes: 0

Views: 964

Answers (2)

Luis Orduz
Luis Orduz

Reputation: 2887

The default properties declared in the exported component are saved in the options property when using Vue.extend.

As such, this could test what you want:

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

It's better this way because options.created is an object, not a function; and what you want is to test that it exists anyway.

Upvotes: 1

Tarun Lalwani
Tarun Lalwani

Reputation: 146510

If you wanted to create a function to be used on the component you need to below

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

And then test it like below

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

If you wanted it as component options then you need to use your original template and use the test as

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

Upvotes: 0

Related Questions