テスト

Vue3アプリケーションのテスト戦略には、ロジックテストとUIテストが含まれます。これらのテストを効果的に実行するために、vitest@vue/test-utilsを使用します。vitestはVueアプリケーションのための高速なユニットテストランナーおよびアサーションライブラリであり、@vue/test-utilsはVueコンポーネントのUIテストをより宣言的に行うためのツールセットを提供します。

プロジェクトのセットアップ

  1. Viteを使用してVue3プロジェクトを作成し、必要なテスト依存関係を追加します。
    npm create vite@latest my-vue-app -- --template vue
    cd my-vue-app
    npm install
    npm install -D vitest @vue/test-utils jsdom @vitejs/plugin-vue
    
  2. vitestを使用するために、vite.config.jsを編集してテストの設定を追加します。 globals: trueとすることでdescribe,it,test,expect,beforeAll,afterAll,beforeEach,afterEach,viなどの関数が自動インポートされ記述量を減らせます。
    vite.config.js
    import { defineConfig } from 'vite';
    import vue from '@vitejs/plugin-vue';
    import { fileURLToPath, URL } from 'url';
    export default defineConfig({
      plugins: [vue()],
      resolve: {
       alias: {
         '@': fileURLToPath(new URL('./src', import.meta.url))
       }
      },
      test: {
        globals: true,
        environment: 'jsdom',
      },
    });
    

ロジックのテストの例

Vue3コンポーネントのロジック(例えば、算術演算を行う関数)をテストします。

src/utils/sum.js
// 単純な加算関数
export function sum(a, b) {
  return a + b;
}
spec/utils/sum.test.js
import { sum } from '@/logic/sum';

describe('sum', () => {
  it('adds two numbers', () => {
    expect(sum(1, 2)).toBe(3);
  });
});

UIのテストの例

@vue/test-utilsを使用して、ユーザーインターフェイスのテストを行います。コンポーネントに入力を提供し、期待される出力を検証します。

src/components/HelloWorld.vue
<script setup>
defineProps({
  msg: String,
});
</script>
<template>
  <div>{{ msg }}</div>
</template>
spec/components/HelloWorld.test.js
import { render } from '@vue/test-utils';
import HelloWorld from '@/components/HelloWorld.vue';

describe('HelloWorld', () => {
  it('renders passed message', () => {
    const { getByText } = render(HelloWorld, {
      props: { msg: 'Hello Vitest' },
    });
    
    expect(getByText('Hello Vitest')).toBeDefined();
  });
});

テストの実行

テストを実行するには、package.jsonにスクリプトを追加し、vitestを使ってテストを実行します。

{
  "scripts": {
    "test": "vitest"
  }
}

コマンドラインで以下を実行します。

npm run test

@vitest/uiとカバレッジツール

必要となるライブラリをインストールします。

npm install -D @vitest/ui @vitest/coverage-v8

coverageの設定を追加します。

vite.config.js
export default defineConfig({
  // 中略
  test: {
    globals: true,
    environment: 'jsdom',
    // 下記を追加
    coverage: {
      provider: 'v8',
      enabled: true
    }
  },
});