0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Vitestの基本的な使い方-テストコード学習2本目

Last updated at Posted at 2025-03-15

概要

このブログ記事は、テストフレームワークを学ぶ過程で執筆した記事の第3回です。
Vitestの基本的な使い方と設定について記載しています。

インストールコマンド

npm

npm install -D vitest

yarn

yarn add -D vitest

オンラインで試すには

ブラウザ上でNode.jsを直接実行できるオンライン開発環境のstackblitzが用意されています。

テストの書き方

sum.ts
export function sum(a: number, b: number): number {
  return a + b
}
sum.test.ts
import { expect, test } from 'vitest'
import { sum } from './sum.ts'

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3)
})

デフォルトでは、テストファイルは名前に「.test.」または「.spec.」を含む必要があります。

テストの実行

package.jsonに、以下のコードを記載します。利用するコマンドを定義しているだけなので、プロジェクトに応じて変えてください。

package.json
{
  "scripts": {
    "test": "vitest"
  }
}

npm

npm run test

yarn

yarn test

テストコマンドを実行後、テスト結果が表示されます。

test/sum.test.ts (1 test) 1ms
   ✓ adds 1 + 2 to equal 3

 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  21:35:38
   Duration  1.63s (transform 73ms, setup 0ms, collect 61ms, tests 1ms, environment 0ms, prepare 442ms)

Vitestの設定

Vitestはvite.config.tsを読み込み、Viteと同じプラグインと設定を読み込みます。resolve.alias(インポートパスを簡略化するための機能)などが設定不要となります。

  • vite.config.tsより優先度の高いファイルとしてvitest.config.tsを作成することもできる。
  • CLIのオプションとして設定ファイルを渡すこともできる。
vitest --config ./path/to/vitest.config.ts
  • process.env.VITESTdefineConfigmodeプロパティを用いて、Vitestを実行する際に固有の設定に変更することが可能。
export default defineConfig({
  // Vitestが実行中の場合のみ適用される設定
  ...(process.env.VITEST
    ? {
        test: {
          // テスト用の特別な設定
          globals: true,
          coverage: {
            reporter: ['text', 'json', 'html'],
          },
        },
      }
    : {}),
});
export default defineConfig(({ mode }) => {
  // modeが'test'の場合(Vitestを実行中)は特別な設定を適用
  const isTest = mode === 'test';

  return {
    resolve: {
      alias: {
        '@': '/src',
        // テスト中のみモックライブラリを使用
        ...(isTest
          ? {
              'api-client': '/src/__mocks__/api-client.ts',
            }
          : {}),
      },
    },
    // テスト用の追加設定
    ...(isTest
      ? {
          test: {
            globals: true,
            coverage: {
              reporter: ['text', 'json', 'html'],
            },
          },
        }
      : {}),
  };
});

参考記事:
https://vitest.dev/guide/

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?