LoginSignup
3
4

More than 5 years have passed since last update.

Vue.js+TypeScriptのテストでRouterLinkがないって怒られたときの対応

Last updated at Posted at 2018-09-06

概要

Vue.jsのRouterはmain.tsで読み込んでると、コンポーネントなどでrouter-link を意識せずに利用できて便利なのですが、コンポーネントの単体テストを書いているとそんなコンポーネント知らない!と怒られるので対応します。

環境

Vue CLIを利用してプロジェクトを用意します。
開発環境やプロジェクト作成方法についてはこちらご参照ください。

DockerでVue.js+TypeScript開発環境を構築する
https://qiita.com/kai_kou/items/d581a9f8f3ee8605aed1

GitHubにも今回利用したソースをUPしていますので、よかったらどうぞ。
https://github.com/kai-kou/vue-js-typescript-import-router-link

再現

以下のようにコンポーネントを作成します。

> touch src/components/Hoge.vue
> vi src/components/Hoge.vue
src/components/Hoge.vue
<template>
  <router-link to="/">
    リンク!
  </router-link>
</template>

<script lang="ts">
  import {
    Component,
    Vue,
  } from 'vue-property-decorator';

  @Component
  export default class Hoge extends Vue {}
</script>

テストも用意します。

> touch tests/unit/Hoge.spec.ts
> vi touch tests/unit/Hoge.spec.ts
tests/unit/Hoge.spec.ts
import { expect } from 'chai';
import { shallowMount } from '@vue/test-utils';

import Hoge from '@/components/Hoge.vue';

describe('Hoge.vue', () => {
  it('RouteLinkが利用できるか', () => {
    const wrapper = shallowMount(Hoge, {});

    wrapper.is(Hoge);
    expect(wrapper.findAll('router_link')).to.length(1);
  });
});

テストを実行します。

> yarn test:unit

  Hoge.vue
[Vue warn]: Unknown custom element: <router-link> - did you register the component correctly? 
For recursive components, make sure to provide the "name" option.

found in

---> <Hoge> at src/components/Hoge.vue
       <Root>
    ✓ RouteLinkが利用できるか (69ms)

  1 passing (119ms)

 MOCHA  Tests completed successfully

はい。
テストはパスしますが、[Vue warn] がでてしまって気持ち悪いです。
モヤモヤします。
なんとかしたいです。

router-linkが認識されるようにテストを変更します。

tests/unit/Hoge.spec.ts
import { expect } from 'chai';
import { createLocalVue, shallowMount } from '@vue/test-utils';
import Router from 'vue-router';

import Hoge from '@/components/Hoge.vue';
const localVue = createLocalVue();
localVue.use(Router);
const RouterLink = localVue.component('router-link');

describe('Hoge.vue', () => {
  it('RouteLinkが利用できるか', () => {
    const wrapper = shallowMount(Hoge, { localVue });

    wrapper.is(Hoge);
    expect(wrapper.findAll(RouterLink)).to.length(1);
  });
});

では、再度テストを実行してみます。

> yarn test:unit

 MOCHA  Testing...

  Hoge.vue
    ✓ RouteLinkが利用できるか (95ms)

  1 passing (264ms)

 MOCHA  Tests completed successfully

やったぜ。

参考

Expose RouterLink and RouterView components #1976
https://github.com/vuejs/vue-router/issues/1976

Vue.js+TypeScriptで開発するときの参考記事まとめ
https://qiita.com/kai_kou/items/19b494a41023d84bacc7

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4