Vue 単一ファイルコンポーネントのユニットテスト

個人開発したアプリの宣伝
目的地が設定できる手帳のような使い心地のTODOアプリを公開しています。
Todo with Location

Todo with Location

  • Yoshiko Ichikawa
  • Productivity
  • Free

スポンサードリンク


vue-test-utils を使用する

テストモジュールと対象のコンポーネントのimport

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


テストケースの記述

describe() & it()

describeに、テストの区分けやテストケース、パターン、テスト対象のコンポーネントパーツ名などを、itに合格条件を記述する。

describe('button', () => {
  it('クラス名がdefault-buttonであること', () => {
   })
})


コンポーネントラッパーの生成

mount() | Vue Test Utils

const button = mount(hogeButton)

propsを渡したコンポーネントを生成したい場合は、以下のように記述できる。

const button = mount(hogeButton, {
    propsData: { key: value }
})


値の検証

Wrapper | Vue Test Utils

凡例。

//ボタンであるか?
expect(button.is('button')).to.equal(true)
//クラス名が指定のものを含むか?
expect(button.classes()).to.include('default-button')
//disableが記述されていないか?
expect(button.attributes().disabled).to.be.an('undefined')
//カスタムアクションを実行
button.trigger('click')
//emitされたイベントの確認
expect(button.emitted().click.length).to.equal(1)


テスト記述例

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

describe('button', () => {
  it('クラス名がdefault-buttonであること', () => {
    const button = mount(hogeButton, {
      propsData: { key: value }
    })

    expect(button.is('button')).to.equal(true)
    expect(button.classes()).to.include('default-button')
    expect(button.attributes().disabled).to.be.an('undefined')
    button.trigger('click')
    expect(button.emitted().click.length).to.equal(1)
   })
})