概要
Vue.jsのUT実施のためにJestを採用
設定関連でたくさん詰まったのでエラーと解決方法をまとめる。
前提
package.jsonに以下の設定を行い「npm test」でテストを実行できる状態にする
"test": "NODE_ENV=test jest",
jest.config.jsを以下のように記載(パスは環境により書き換える)
module.exports = {
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/$1',
'^~/(.*)$': '<rootDir>/$1',
'^vue$': 'vue/dist/vue.common.js'
},
moduleFileExtensions: ['js', 'vue', 'json'],
transform: {
'^.+\\.js$': 'babel-jest',
'.*\\.(vue)$': 'vue-jest'
},
collectCoverage: false,
collectCoverageFrom: [
'<rootDir>/components/**/*.vue',
'<rootDir>/pages/**/*.vue'
]
}
以下のコマンドで必要なパッケージをインストールしておく
npm i --save-dev vue-jest
npm i jest --save
npm i @vue/test-utils
[エラー①]Requires Babel "^7.0.0-0", but was loaded with "6.xx.x"
Requires Babel "^7.0.0-0", but was loaded with "6.xx.x". If you are sure you have a compatible version of @babel/core, it is likely that something in your build process is loading the wrong version. Inspect the stack trace of this error to look for the first entry that doesn't mention "@babel/core" or "babel-core" to see what is calling Babel.
npm test実行時に上記のエラーが発生。
上記より以下のコマンドを実行することにより回避
npm install --save-dev "babel-core@^7.0.0-bridge.0"
ただし、babel-coreのバージョンを変更することになるので、既存バージョンを考慮した上で変更すること。
[エラー②]Your test suite must contain at least one test.
npm test実行時に上記のエラーが発生。
以下のコマンドを実行して、jsdomをインストールすることにより回避
npm install --save-dev jsdom jsdom-global
対象のテストファイルに記載(setupファイルがあればそちらに記載する)
require('jsdom-global')()
[エラー③]Cannot read property 'child' of undefined
jest.config.js直下に以下の設定を追加
testEnvironment: "jsdom",
https://github.com/vuejs/vue-test-utils/issues/1192