[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.
おわりに
ここまででテストを実行する土台が整いました。
これから実際のコンポーネントテストをどのように書くか学んでアウトプットします!
Author And Source
この問題について([Vue.js][Jest]コンポーネントの単体テストを実行できるようにする), 我々は、より多くの情報をここで見つけました https://qiita.com/tocomi/items/200001a8f106d2f6a69d著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .