
Vue と Jest で Unit test を始めよう
この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
Vue と Jest で Unit test を始めよう
保守性の高いコードが書けていますか?
VueのComponent構成 ~ Unit test までの流れを書いています。
Unit testがあると、保守しながら長くメンテナンスしていけるコードになるので、
開発の助力になればと思います。
本題の前に
Vue とは
オープンソースのJavaScriptフレームワークであり、
フロント系では、3大フレームワークと言われ、わかりやすい構文の為人気があります。
Jest とは
JavaScriptのUnit testのためのツールです。
わかる事
Atomic Componentのディレクトリ構成 (atoms)atomsのComponentのUnit test
触れないこと
Vue,Jestの基本的な構文
Atomic Component のディレクトリ構成
Unit testする場合、このようなディレクトリ構成が見通し良いのでおすすめです。
$ tree
atoms/
└── MyButton
├── index.test.js
└── index.vue
アンチパターンではありませんが 下記の様なディレクトリ構成の場合
MyButtonとmyButtonでファイル名に統一性がないMyButton.story.tsxなどを追加したい場合さらに増える (*storybook)- 全体の見通しが悪い
$ tree atoms/ ├── myButton.test.js └── MyButton.vue
Reactで開発する際も、この構成で開発しています。
ComponentのUnit test
Componentの概要
props で ボタンのテキストをうけとる
click 時は$emitで、親componentの処理を呼び出す
と なんの変哲もないcomponentです。
<!--index.vue-->
<template>
<button
@click="$emit('myAction')"
>
{{ txt }}
</button>
</template>
<script>
export const props = {
txt: {
type: String,
required: true
},
}
export default {
props
}
</script>
Unit testの概要
ボタンテキストが正しく表示されているか確認
clickイベントの確認
// index.test.js
import { shallowMount } from '@vue/test-utils'
import MyButton from '@/components/atoms/MyButton'
describe('MyButton', () => {
const props = {
txt: 'MyButtonTxt',
}
it('ボタンテキストが正しく表示されているか確認', () => {
// propsを受け取り shallowMountし テスト対象component生成
const wrapper = shallowMount(MyButton, { propsData: { ...props } })
// {{ txt }}にpropsで受け取った値が表示されているか確認
expect(wrapper.text()).toBe(props.txt)
})
it('clickイベントの確認', () => {
// propsを受け取り shallowMountし テスト対象component生成
const wrapper = shallowMount(MyButton, { propsData: { ...props } })
expect(wrapper.emitted('myAction')).toBeUndefined()
// clickイベント実行
wrapper.trigger('click')
// myActionが実行されたか確認
expect(wrapper.emitted('myAction')).toBeTruthy()
})
})
まとめ
Atomic Component の構成にすることのメリット
- テストがしやすい
- ディレクトリの見通しが良い
- 再利用性が高い
Atomic Component の構成にすることのデメリット
- 1ファイル全て書く方式よりは、ファイル数が増える
1ファイルの行数が長いとUnit testの際に苦労する場合が多いです。
実際の開発では、機能追加が発生すると思います。
その際バグを含まない用に、Unit testをしっかり導入していきましょう。








