LoginSignup
1
0

Vitest と Playwright でテスト実行

Last updated at Posted at 2024-03-10

はじめに

この記事では、Vitest と Playwright という2つテストを実行するための設定方法について記載します。

開発環境

開発環境は以下の通りです。

  • Windows11
  • VSCode
  • Node.js 20.5.0
  • yarn 1.22.19
  • TypeScript 5.3.3
  • React 18.2.0
  • Vitest 1.3.1
  • Playwright 1.42.1

背景

元々 Vitest を利用して、単体テストや結合テストを書いているプロジェクトがありました。そちらに E2E テストとして、Playwright をインストールしました。インストール直後のテストファイルの構成やテスト実行のスクリプト、設定ファイルは以下の通りです。

image.png

package.json
{
  ...
  "scripts": {
    "test": "vitest",
    ...
  }, 
  ...
}
vite.config.ts
import react from "@vitejs/plugin-react";
import type { UserConfig } from "vite";
import { defineConfig } from "vite";
import type { InlineConfig } from "vitest";

interface VitestConfigExport extends UserConfig {
  test: InlineConfig;
}

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  server: {
    port: 3000,
    open: true,
  },
  test: {
    globals: true,
    environment: "jsdom",
    setupFiles: "./src/__tests__/setup.ts",
  },
} as VitestConfigExport);

この状態でテストを実行すると、以下のように Playwright を利用しているテストファイルでエラーが発生します。

image.png

そのため、Vitest と Playwright のテストを別々に実行できるようにしていきます。

Vitest のテスト実行スクリプト

Vitest は vite.config.ts でテスト実行ファイルを unitintegration に限定することで、エラーなく、実行できるようになりました。

vite.config.ts
import react from "@vitejs/plugin-react";
import type { UserConfig } from "vite";
import { defineConfig } from "vite";
import type { InlineConfig } from "vitest";

interface VitestConfigExport extends UserConfig {
  test: InlineConfig;
}

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  server: {
    port: 3000,
    open: true,
  },
  test: {
    include: [
      "**/unit/*.{test,spec}.?(c|m)[jt]s?(x)",
      "**/integration/**/*.{test,spec}.?(c|m)[jt]s?(x)",
    ],
    globals: true,
    environment: "jsdom",
    setupFiles: "./src/__tests__/setup.ts",
  },
} as VitestConfigExport);

image.png

Playwright テスト実行スクリプト

Playwright はテスト実行のコマンドをスクリプトを追加するだけで、エラーなく実行できるようになりました。

package.json
{
  ...
  "scripts": {
    ...
    "test:playwright": "playwright test",
    ...
  }, 
  ...
}

image.png

参考

1
0
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
1
0