Vue.jsアプリケーションをテストすることの重要性は控えめに言ってはいけません。Jestはこれをこれまで以上に簡単にします。

Vue.js環境内にいるので、ネイティブVue要素とのインターフェースを簡単にするためにvue-test-utilsも使用します。

プロジェクトの設定

テスト環境のセットアップは簡単です。 以前のバージョンのVue.jsCLIでは、これを手動で行う必要がありましたが、現在はプロジェクト生成に標準で付属しています。

次の手順を実行して、 Vue.jsCLIがマシンにインストールされていることを確認します。

$ npm install -g @vue/cli
# OR
$ yarn global add @vue/cli

# Ensure you have the appropriate version (3.x.x>) with
$ vue --version

次のCLIを使用して新しいプロジェクトを作成します。

$ vue create testing-vue

> Manually select features
> Babel, Linter / Preformatter, Unit Testing
> ESLint (your preference)
> Lint on save
> Jest
> In dedicated config files

$ cd testing-vue
$ code .
$ npm run serve 

テスト

Jestを使用してVueプロジェクトを生成したので、tests/unitフォルダーに移動できます。 このフォルダ内に、example.spec.jsという名前のファイルがあります。

import { shallowMount } from "@vue/test-utils";
import HelloWorld from "@/components/HelloWorld.vue";

describe("HelloWorld.vue", () => {
  it("renders props.msg when passed", () => {
    const msg = "new message";
    const wrapper = shallowMount(HelloWorld, {
      propsData: { msg }
    });
    expect(wrapper.text()).toMatch(msg);
  });
});

package.json内で参照されているように、次のように入力してこの単体テストを実行できます。

$ npm run test:unit

これにより、プロジェクト内のすべての単体テストの結果が得られます。 現時点では、すべてが期待どおりに通過します。

これに--watchフラグを追加して、新しいテストを作成および編集するときにこれをバックグラウンドで実行し続けることができます。

"scripts": {
  "test:unit": "vue-cli-service test:unit --watch"
}

ユニットテスト

この小さな例では、FancyHeadingという名前の新しいコンポーネントを作成します。 これは、小道具を使用してtitleおよびcolorでカスタマイズできる見出しを表します。

<template>
  <h1 :style="headingStyles">{{title}}</h1>
</template>

<script>
export default {
  data() {
    return {
      headingStyles: {
        color: this.color
      }
    };
  },
  props: ["title", "color"]
};
</script>

これを単体テストするには、tests/unitディレクトリ内に対応するFancyHeading.spec.jsファイルを作成する必要があります。

テストスイートは、特定のモジュールまたは機能のテストを中心としたテストのコレクションと考えることができます。

JestとVueを使用した最初の単体テストを見てみましょう。 行ごとに調査します。

import Vue from 'vue';
import FancyHeading from '@/components/FancyHeading.vue';

function mountComponentWithProps (Component, propsData) {
  const Constructor = Vue.extend(Component);
  const vm = new Constructor({
    propsData
  }).$mount();

  return vm.$el;
}

describe('FancyHeading.vue', () => {
  it('should be the correct color', () => {
    const headingData = mountComponentWithProps(FancyHeading, { color: 'red' });
    const styleData = headingData.style.getPropertyValue('color');

    console.log(styleData)

    expect(styleData).toEqual('blue');
  });

  it('should have the correct title', () => {
    const headingData = mountComponentWithProps(FancyHeading, { title: 'Hello, Vue!' });
    const titleData = headingData.textContent;

    expect(titleData).toEqual('Hello, Vue!');
  });
});
  1. まず、Vueとテストする必要のあるコンポーネントをインポートします。
  2. describeを使用して、FancyHeadingコンポーネントを取り巻く多数の単体テストをカプセル化します。
  3. 各単体テストはit関数を使用して作成され、最初にテスト対象の正確な説明を提供し、次に関数を提供します。
  4. 最初のアサーションIt must have the correct colorでは、コンポーネントをmountComponentWithPropsを使用して新しいVueインスタンスにマウントしています。
  5. 次に、テストから受け取ると予想されるを含む変数styleDataを作成できます。
  6. 最後に、expectを使用して、これが当てはまると断言します。 $ npm run test:unit --watchで端末を確認すると、この単体テストのPASSが表示されます。

2番目の単体テストで見出しのタイトルをテストするときも、同様のアプローチを取ります。

Vue.jsを使用したテストの詳細については、 JosephBemenderferによるKarmaandMochaガイドをご覧ください。