【Jest】Vueのテストを書こう!


Vueのテストを書こう!

Vue.jsのコンポーネントのテストについてナレッジを貯めていきます。(随時追加)

  1. テキスト表示についてのテスト
  2. DOM要素についてのテスト
  3. 子コンポーネントをスタブにしてテスト
  4. コンポーネントのfactory関数を定義する

テキスト表示についてのテスト

import { mount } from '@vue/test-utils'
import HelloWorld from '@/components/HelloWorld.vue'

describe('HelloWorld.vue', () => {
  it('renders a HelloWorld', () => {
    const wrapper = mount(HelloWorld)

    expect(wrapper.text()).toMatch("HelloWorld!!")
  })
})

DOM要素についてのテスト


import { mount } from '@vue/test-utils'
import HelloWorld from '@/components/HelloWorld.vue'

describe('HelloWorld.vue', () => {
  it('renders a HelloWorld', () => {
    const wrapper = mount(HelloWorld)
    expect(wrapper.html()).toMatch("<div><p>HelloWorld!!</p></div>")
  })
})

子コンポーネントをスタブにしてテスト

shallowMountメソッドで子コンポーネントをスタブ(代替えの偽物)としてマウントします。
mountだと子コンポーネントまですべてマウントされます。

const shallowWrapper = shallowMount(Parent)
console.log(shallowWrapper.html())
  • ログの結果

子コンポーネントが<vuecomponent-stub />とスタブとなって出力されています。

<div><vuecomponent-stub></vuecomponent-stub></div>

コンポーネントのfactory関数を定義する

一番上にvaluesオブジェクトをまとめてdataにして、新しいwrapperインスタンスを返すファクトリ関数を宣言します。

このようにすると、すべてのテストでconst wrapper = shallowMount(Foo)を複製する必要がありません

import { shallowMount } from '@vue/test-utils'
import Foo from './Foo'

const factory = (values = {}) => {
  return shallowMount(Foo, {
    data () {
      return {
        ...values
      }
    }
  })
}

describe('Foo', () => {
  it('welcome メッセージを描画する', () => {
    const wrapper = factory()

    expect(wrapper.find('.message').text()).toEqual("Welcome to the Vue.js cookbook")
  })

  it('usernameが7未満のときエラーを描画する', () => {
    const wrapper = factory({ username: ''  })

    expect(wrapper.find('.error').exists()).toBeTruthy()
  })

  it('usernameが空白のときエラーを描画する', () => {
    const wrapper = factory({ username: ' '.repeat(7) })

    expect(wrapper.find('.error').exists()).toBeTruthy()
  })

  it('usernameが7文字かそれ以上のとき、エラーが描画されない', () => {
    const wrapper = factory({ username: 'Lachlan' })

    expect(wrapper.find('.error').exists()).toBeFalsy()
  })
})

参考URL

Vue.js 公式サイト

vue-test-utils 公式サイト

vue-testing-handbook
➡︎より実践的な使い方がわかる