[Vue.js][Jest]コンポーネントの単体テストを実行できるようにする


既存のVueアプリにコンポーネントテストを追加しようとしたときのお話です。

公式にサポートページがあるからそれでやればできるかなと思ったけど、
そのままの手順だといくつか躓いたので自分の対応を残しておきます。
Vueのバージョンが最新じゃないのが原因かもしれない。。

環境

Version
macOS Mojave 10.14.6
vue 2.5.18
node 10.5.0

セットアップ

公式サポート

Jest を使用した単一ファイルコンポーネントのテスト | Vue Test Utils

jestのインストール

yarn add --dev jest @vue/test-utils
package.json
{
  "scripts": {
    ...
+   "test": "jest"
    ...
  }
}

*.vueファイルを処理するための設定

yarn add --dev vue-jest
package.json
+ "jest": {
+   "moduleFileExtensions": [
+     "js",
+     "json",
+     "vue"
+   ],
+   "transform": {
+     ".*\\.(vue)$": "vue-jest"
+   }
+ },

webpackのエイリアス設定

package.json
  "jest": {
    ...
+   "moduleNameMapper": {
+     "^@/(.*)$": "<rootDir>/src/$1"
+   }
  },

Babel設定

yarn add --dev babel-jest babel-core
package.json
  "jest": {
    ...
    "transform": {
      ...
+     "^.+\\.js$": "<rootDir>/node_modules/babel-jest"
    },
  },
.babelrc
+ {
+   "presets": [[ "@babel/env", { "modules": false } ]],
+   "env": {
+     "test": {
+       "presets": [[ "@babel/env", { "targets": { "node": "current" } } ]]
+     }
+   }
+ }

自分の場合はここまでやるとテストを実行することが出来ました。

テストの作成

ディレクトリ構成

ベストプラクティスはわからないけど、srcフォルダと同じ階層となるようにtestフォルダを作成しました。

├─src
│  └─Components
│      └─hoge.vue
└─test
    └─Components
        └─hoge.spec.js

テストの記述

hoge.spec.js
import { mount } from '@vue/test-utils'
import hoge from '@/components/hoge.vue'

describe('Component', () => {
  test('is a Vue instance', () => {
    const wrapper = mount(hoge)
    expect(wrapper.element).toMatchSnapshot()
  })
})

公式サポートのサンプルを元に作成しています。
(toMatchSnapshot()って何をテストしているのだろう。。)

テストの実行

yarn testでテストが実行されます。
問題なく実行されれば下記のようなログが出ます!

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   1 passed, 1 total
Time:        1.749s, estimated 2s
Ran all test suites.
✨  Done in 2.61s.

おわりに

ここまででテストを実行する土台が整いました。
これから実際のコンポーネントテストをどのように書くか学んでアウトプットします!