Vue.jsでテスト可能なコンポーネント開発を行うためのヘッドレステスト法

Vue.jsでテスト可能なコンポーネント開発を行うためのヘッドレステスト法

Vue.jsコンポーネントをテスト可能にするヘッドレステスト法は、信頼性と保守性の高いコードベースを構築するために重要です。本記事では、ヘッドレステストを用いてVue.jsコンポーネントを効果的にテストする方法を解説します。

ヘッドレステストとは

ヘッドレステストは、ブラウザUIを介さずにJavaScriptアプリケーションを自動テストする手法です。

npm install --save-dev @vue/test-utils jest

テスト環境のセットアップ

JestやVue Test Utilsを使用してテスト環境をセットアップします。

module.exports = {
  preset: '@vue/cli-plugin-unit-jest'
}

テスト対象のコンポーネントの準備

シンプルなコンポーネントを用意してテスト対象とします。

<template>
  <button @click="increment">{{ count }}</button>
</template>
<script>
export default {
  data() {
    return { count: 0 }
  },
  methods: {
    increment() {
      this.count++
    }
  }
}
</script>

単体テストの基本

単体テストでコンポーネントの動作を確認します。

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

test('increments count when button is clicked', () => {
  const wrapper = mount(Counter)
  wrapper.find('button').trigger('click')
  expect(wrapper.text()).toContain('1')
})

Propsのテスト

Propsを通じた動作をテストします。

test('renders prop value correctly', () => {
  const wrapper = mount(Counter, {
    props: { initialCount: 5 }
  })
  expect(wrapper.text()).toContain('5')
})

イベントのテスト

子コンポーネントのイベント発火をテストします。

test('emits an event when clicked', () => {
  const wrapper = mount(Counter)
  wrapper.vm.$emit('increment')
  expect(wrapper.emitted('increment')).toBeTruthy()
})

スナップショットテスト

UIの状態をスナップショットとして保存し、変更を検出します。

test('matches snapshot', () => {
  const wrapper = mount(Counter)
  expect(wrapper.html()).toMatchSnapshot()
})

ヘッドレスブラウザを使用する

Puppeteerを使用してヘッドレスブラウザでE2Eテストを行います。

const puppeteer = require('puppeteer')
test('renders page title', async () => {
  const browser = await puppeteer.launch()
  const page = await browser.newPage()
  await page.goto('http://localhost:8080')
  const title = await page.title()
  expect(title).toBe('My App')
  await browser.close()
})

コンポーネントの依存関係をモックする

外部依存関係をモックしてテストを安定化します。

jest.mock('@/api', () => ({
  fetchData: () => Promise.resolve('mock data')
}))

非同期処理のテスト

非同期関数の結果をテストします。

test('handles async data correctly', async () => {
  const wrapper = mount(Counter)
  await wrapper.vm.loadData()
  expect(wrapper.text()).toContain('mock data')
})

エラーハンドリングのテスト

エラー発生時の挙動をテストします。

test('displays error message on failure', async () => {
  const wrapper = mount(Counter)
  await wrapper.vm.loadDataWithError()
  expect(wrapper.text()).toContain('Error occurred')
})

複数のコンポーネントを統合テスト

複数のコンポーネントが適切に動作するか統合テストを行います。

test('parent-child communication works', () => {
  const parentWrapper = mount(ParentComponent)
  const childWrapper = parentWrapper.findComponent(ChildComponent)
  childWrapper.vm.$emit('childEvent')
  expect(parentWrapper.text()).toContain('Child Event Triggered')
})

まとめ

ヘッドレステスト法を活用することで、Vue.jsコンポーネントを効率的にテストし、エラーを早期発見できます。JestやPuppeteerなどのツールを適切に活用し、堅牢なアプリケーションを構築しましょう。