Vue.jsでのユニットテストとE2Eテストを実現: CypressとJestの使い方

Vue.jsでのユニットテストとE2Eテストを実現: CypressとJestの使い方

Vue.jsでのユニットテストとE2E(End-to-End)テストは、アプリケーションの品質を保つために非常に重要です。この記事では、Vue.jsでJestを使用したユニットテストと、Cypressを使用したE2Eテストの実装方法を詳述します。

ユニットテストとE2Eテストの違い

ユニットテストは、アプリケーションの各コンポーネントや関数が期待通りに動作するかを検証するテストであり、E2Eテストはアプリケーション全体のフローをテストして、ユーザーが実際に操作する流れをシミュレートするものです。

Jestのインストールと設定

Jestは、Vue.jsのユニットテストで最も広く使用されているテストフレームワークの一つです。まず、Jestをプロジェクトにインストールします。

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

Jestの基本的な使い方

Jestを使ったユニットテストは、[code]describe[/code]と[code]it[/code]を使って、テストケースを作成します。

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

describe('MyComponent', () => {
  it('renders the correct message', () => {
    const wrapper = mount(MyComponent);
    expect(wrapper.text()).toBe('Hello World');
  });
});

Vue.jsコンポーネントのテスト

Vueコンポーネントのユニットテストでは、mount関数を使ってコンポーネントをマウントし、DOM要素の状態やイベントを確認することができます。

it('should display the correct title', () => {
  const wrapper = mount(MyComponent, {
    props: { title: 'Test Title' }
  });
  expect(wrapper.find('h1').text()).toBe('Test Title');
});

Vue.jsのライフサイクルフックとテスト

コンポーネントのライフサイクルフックをテストすることもできます。たとえば、[code]mounted[/code]フックが呼ばれたことを確認するテストを追加できます。

it('calls mounted hook', () => {
  const spy = jest.spyOn(MyComponent.methods, 'mounted');
  mount(MyComponent);
  expect(spy).toHaveBeenCalled();
});

Vuexストアを使ったテスト

Vuexを使ったユニットテストでは、ストアの状態やアクション、ミューテーションの挙動を確認できます。

import store from '@/store';

it('updates the store state', async () => {
  const wrapper = mount(MyComponent, {
    global: {
      plugins: [store]
    }
  });
  await wrapper.find('button').trigger('click');
  expect(store.state.counter).toBe(1);
});

Cypressのインストールと設定

CypressはE2Eテストを行うための強力なツールです。まず、Cypressをインストールします。

npm install --save-dev cypress

Cypressの基本的な使い方

Cypressを使って、ユーザーがブラウザ上でどのようにインタラクションするかをテストすることができます。

describe('MyComponent E2E Test', () => {
  it('should navigate to the about page', () => {
    cy.visit('/');
    cy.contains('About').click();
    cy.url().should('include', '/about');
  });
});

UI要素の操作と検証

Cypressでは、UI要素を操作して、その結果を検証することができます。例えば、ボタンをクリックした後に表示される内容を確認できます。

it('should show the correct message on button click', () => {
  cy.visit('/');
  cy.get('button').click();
  cy.get('.message').should('contain', 'Button clicked!');
});

フォームのテスト

フォームの入力や送信をテストすることもできます。Cypressでは、フォーム要素に値を入力して送信する動作をシミュレートできます。

it('should submit the form', () => {
  cy.visit('/contact');
  cy.get('input[name="name"]').type('John Doe');
  cy.get('textarea[name="message"]').type('This is a test message');
  cy.get('form').submit();
  cy.contains('Thank you for your message!').should('be.visible');
});

APIのレスポンスのモック

Cypressでは、APIのレスポンスをモックして、外部依存性を排除し、テスト環境を安定させることができます。

it('should mock API response', () => {
  cy.intercept('GET', '/api/user', { fixture: 'user.json' }).as('getUser');
  cy.visit('/profile');
  cy.wait('@getUser');
  cy.get('.user-name').should('contain', 'John Doe');
});

テストの実行とCIへの統合

テストを実行するために、JestとCypressをCIツール(例:GitHub ActionsやTravis CI)に統合することで、継続的にテストを実行し、コードの品質を保つことができます。

# GitHub Actionsの設定例
name: CI

on: [push]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v2
      - name: Set up Node.js
        uses: actions/setup-node@v2
        with:
          node-version: '14'
      - name: Install dependencies
        run: npm install
      - name: Run Jest tests
        run: npm run test
      - name: Run Cypress tests
        run: npm run cypress:run

テストのカバレッジを確認する

JestやCypressを使用して、テストのカバレッジを確認することができます。カバレッジレポートを生成することで、テストがどの部分に不足しているかを把握することができます。

npm install --save-dev jest-coverage

ユニットテストとE2Eテストのベストプラクティス

テストを書く際には、テストが独立しており、再現可能で、簡単に理解できるようにすることが大切です。ユニットテストとE2Eテストのバランスを取り、必要なカバレッジを確保しましょう。

it('should test a simple feature correctly', () => {
  const wrapper = mount(MyComponent);
  expect(wrapper.vm.someMethod()).toBe(true);
});