mcpField
W
windows-git-bash-testing

windows-git-bash-testing

github.com/josiahsiegelテスト・品質59159 回インストール19 週間前に更新
リポジトリ

windows-git-bash-testing について

Windows、特に Git Bash/MINGW でテストを実行する開発者向けの互換性ガイドです。Vitest、Playwright、MSW の設定、パス処理、シェル検出、問題解決を扱います。

主な機能

  1. 01Git Bash/MINGW 環境の検出
  2. 02自動パス変換の問題回避
  3. 03クロスプラットフォーム向けテストパス設定
  4. 04シェル環境に応じた Playwright 設定
  5. 05MSW のインポートと Fetch の設定

活用シーン

  1. 01Git Bash での Vitest テスト実行
  2. 02Playwright の E2E テスト設定
  3. 03Windows のテストパスエラーの診断
  4. 04クロスプラットフォームテストと CI の設定

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/josiahsiegel/claude-plugin-marketplace --skill windows-git-bash-testing

インストール後、Claude Code で/windows-git-bash-testingを入力して読み込まれたか確認します。

詳細

Windows と Git Bash のテスト互換性ガイド

概要

このガイドでは、Windows、特に Git Bash/MINGW 環境で Vitest、Playwright、MSW のテストを実行するために必要な知識を説明します。よくあるパス変換の問題、シェルの検出、クロスプラットフォームでのテスト実行パターンを取り上げます。

テスト環境でのシェルの検出

Git Bash/MINGW の検出

Git Bash または MINGW 環境でテストを実行する場合は、次の検出方法を使用してください。

方法 1:環境変数(最も信頼性が高い)

// Detect Git Bash/MINGW in Node.js test setup
function isGitBash() {
  return !!(process.env.MSYSTEM); // MINGW64, MINGW32, MSYS
}

function isWindows() {
  return process.platform === 'win32';
}

function needsPathConversion() {
  return isWindows() && isGitBash();
}

方法 2:セットアップスクリプトで uname を使用する

# In bash test setup scripts
case "$(uname -s)" in
  MINGW64*|MINGW32*|MSYS_NT*)
    # Git Bash/MINGW environment
    export TEST_ENV="mingw"
    ;;
  CYGWIN*)
    # Cygwin environment
    export TEST_ENV="cygwin"
    ;;
  Linux*)
    export TEST_ENV="linux"
    ;;
  Darwin*)
    export TEST_ENV="macos"
    ;;
esac

方法 3:テスト設定での組み合わせ検出

// vitest.config.js or test setup
import { execSync } from 'child_process';

function detectShell() {
  // Check MSYSTEM first (most reliable for Git Bash)
  if (process.env.MSYSTEM) {
    return { type: 'mingw', subsystem: process.env.MSYSTEM };
  }

  // Try uname if available
  try {
    const uname = execSync('uname -s', { encoding: 'utf8' }).trim();
    if (uname.startsWith('MINGW')) return { type: 'mingw' };
    if (uname.startsWith('CYGWIN')) return { type: 'cygwin' };
    if (uname === 'Darwin') return { type: 'macos' };
    if (uname === 'Linux') return { type: 'linux' };
  } catch {
    // uname not available (likely Windows cmd/PowerShell)
  }

  return { type: 'unknown', platform: process.platform };
}

const shell = detectShell();
console.log('Running tests in:', shell.type);

パス変換の問題と解決策

よくあるパス変換の問題

Git Bash は Unix 形式のパスを Windows 形式のパスに自動変換するため、テストファイルのパス、モジュールのインポート、テスト設定で問題が発生することがあります。

問題の例:

# Git Bash converts these automatically:
/foo → C:/Program Files/Git/usr/foo
/foo:/bar → C:\msys64\foo;C:\msys64\bar
--dir=/foo → --dir=C:/msys64/foo
解決策 1:パス変換を無効にする

パス変換によって問題が発生するテストコマンドでは、次のようにします。

# Disable all path conversion for a single command
MSYS_NO_PATHCONV=1 vitest run

# Disable for specific patterns
export MSYS2_ARG_CONV_EXCL="--coverage.reporter"
vitest run --coverage.reporter=html

# Disable for entire test session
export MSYS_NO_PATHCONV=1
npm test
解決策 2:設定で Windows ネイティブのパスを使用する

設定でテストファイルのパスを指定する場合は、Windows 形式のパスを使用してください。

// vitest.config.js - Windows-compatible
export default defineConfig({
  test: {
    include: [
      'tests/unit/**/*.test.js',     // Relative paths work best
      'tests/integration/**/*.test.js'
    ],
    // Avoid absolute paths starting with /c/ or C:
    setupFiles: ['./tests/setup.js'], // Use relative paths
    coverage: {
      reportsDirectory: './coverage'  // Relative, not absolute
    }
  }
});
解決策 3:テストユーティリティ用のパス変換ヘルパー

テストユーティリティでパスを変換するためのヘルパーを作成します。

// tests/helpers/paths.js
import { execSync } from 'child_process';

/**
 * Convert Windows path to Unix path for Git Bash compatibility
 */
export function toUnixPath(windowsPath) {
  if (!needsPathConversion()) return windowsPath;

  try {
    // Use cygpath if available
    return execSync(`cygpath -u "${windowsPath}"`, {
      encoding: 'utf8'
    }).trim();
  } catch {
    // Fallback: manual conversion
    // C:\Users\foo → /c/Users/foo
    return windowsPath
      .replace(/\\/g, '/')
      .replace(/^([A-Z]):/, (_, drive) => `/${drive.toLowerCase()}`);
  }
}

/**
 * Convert Unix path to Windows path
 */
export function toWindowsPath(unixPath) {
  if (!needsPathConversion()) return unixPath;

  try {
    return execSync(`cygpath -w "${unixPath}"`, {
      encoding: 'utf8'
    }).trim();
  } catch {
    // Fallback: manual conversion
    // /c/Users/foo → C:\Users\foo
    return unixPath
      .replace(/^\/([a-z])\//, (_, drive) => `${drive.toUpperCase()}:\\`)
      .replace(/\//g, '\\');
  }
}

function needsPathConversion() {
  return !!(process.env.MSYSTEM ||
           (process.platform === 'win32' && process.env.TERM === 'cygwin'));
}

テストでの使用方法:

import { toUnixPath, toWindowsPath } from '../helpers/paths.js';

test('loads config file', () => {
  const configPath = toWindowsPath('/c/project/config.json');
  const config = loadConfig(configPath);
  expect(config).toBeDefined();
});

Windows/Git Bash でのテスト実行のベストプラクティス

1. クロスプラットフォーム互換性のための NPM スクリプト

すべての環境で動作するテストスクリプトを package.json で定義します。

{
  "scripts": {
    "test": "vitest run",
    "test:unit": "vitest run tests/unit",
    "test:integration": "vitest run tests/integration",
    "test:watch": "vitest watch",
    "test:coverage": "vitest run --coverage",
    "test:e2e": "playwright test",
    "test:e2e:headed": "playwright test --headed",
    "test:debug": "vitest run --reporter=verbose"
  }
}

vitest/playwright コマンドを直接実行するのではなく、必ず npm スクリプトを使用してください。これにより、シェル間で一貫した動作が保証されます。

2. 相対パスでのインポート

パス変換の問題を避けるため、テストファイルでは相対パスを使用してください。

// ✅ Good - Relative paths work everywhere
import { myFunction } from '../../src/utils.js';
import { server } from '../mocks/server.js';

// ❌ Bad - Absolute paths can cause issues in Git Bash
import { myFunction } from '/c/project/src/utils.js';
3. テストファイルの検出

Vitest と Playwright では、Git Bash でのファイルパターンの扱いが異なります。

// vitest.config.js - Use glob patterns, not absolute paths
export default defineConfig({
  test: {
    // ✅ Good - Glob patterns work cross-platform
    include: ['tests/**/*.test.js', 'src/**/*.test.js'],

    // ❌ Bad - Absolute paths problematic in Git Bash
    include: ['/c/project/tests/**/*.test.js']
  }
});
// playwright.config.js - Relative directory paths
export default defineConfig({
  // ✅ Good
  testDir: './tests/e2e',

  // ❌ Bad
  testDir: '/c/project/tests/e2e'
});
4. 一時ファイルの取り扱い

Git Bash では Unix 形式の一時ディレクトリが使用されるため、問題が発生することがあります。

// tests/setup.js - Cross-platform temp file handling
import os from 'os';
import path from 'path';

function getTempDir() {
  const tmpdir = os.tmpdir();

  // In Git Bash, os.tmpdir() may return Windows path
  // Ensure it's usable by your test framework
  if (process.env.MSYSTEM && !tmpdir.startsWith('/')) {
    // Convert Windows temp path if needed
    return tmpdir.replace(/\\/g, '/');
  }

  return tmpdir;
}

// Use in tests
const testTempDir = path.join(getTempDir(), 'my-tests');

Playwright 固有の Windows/Git Bash に関する考慮事項

1. Git Bash でのブラウザーのインストール
# Use npx to ensure correct path handling
npx playwright install

# If issues occur, use Windows-native command prompt instead
# Then run tests from Git Bash
2. MINGW でのヘッド付きモード

Git Bash でヘッド付きテストを実行する場合は、DISPLAY 変数が設定されていないことを確認してください。

# Unset DISPLAY if set (can interfere with Windows GUI)
unset DISPLAY

# Run headed tests
npx playwright test --headed
3. スクリーンショットと動画のパス

成果物には相対パスを使用してください。

// playwright.config.js
export default defineConfig({
  use: {
    // ✅ Good - Relative paths
    screenshot: 'only-on-failure',
    video: 'retain-on-failure',
  },
  // Output directory with relative path
  outputDir: './test-results',
});

Git Bash での MSW(Mock Service Worker)

MSW は通常、Git Bash で問題なく動作しますが、次の点に注意してください。

1. ハンドラーファイルのインポート

MSW のセットアップでは相対パスでインポートしてください。

// tests/mocks/server.js
// ✅ Good
import { handlers } from './handlers.js';

// ❌ Bad - Avoid absolute paths
import { handlers } from '/c/project/tests/mocks/handlers.js';
2. Fetch ポリフィル(Node.js)

ネイティブ Fetch API をサポートする Node.js バージョン 18 以降を使用してください。

# Check Node version
node --version  # Should be 18+

# If using older Node, MSW 2.x won't work properly

Windows/Git Bash でよくあるテストエラーと対処法

エラー 1:Git Bash で「No such file or directory」が表示される

症状:

Error: /usr/bin/bash: line 1: C:UsersUsername...No such file

原因: パス変換の問題。特に一時ディレクトリでよく発生します。

対処法:

# Option 1: Disable path conversion
MSYS_NO_PATHCONV=1 npm test

# Option 2: Use Claude Code's Git Bash path variable
export CLAUDE_CODE_GIT_BASH_PATH="C:\\Program Files\\git\\bin\\bash.exe"

# Option 3: Run via npm scripts (recommended)
npm test  # npm handles path issues automatically
エラー 2:モジュールのインポートに失敗する

症状:

Error: Cannot find module '../src/utils'

原因: パス区切り文字(バックスラッシュとスラッシュ)の混同。

対処法:

// Use path.join() or path.resolve() for cross-platform paths
import path from 'path';

const utilsPath = path.resolve(__dirname, '../src/utils.js');
const utils = await import(utilsPath);
エラー 3:Playwright のブラウザー起動に失敗する

症状:

Error: Failed to launch browser

原因: Git Bash の環境変数がブラウザーの起動に干渉しています。

対処法:

# Clear problematic environment variables
unset DISPLAY
unset BROWSER

# Run Playwright tests
npx playwright test
エラー 4:カバレッジレポートのパスの問題

症状:

Error: Failed to write coverage to /c/project/coverage

対処法:

// vitest.config.js - Use relative paths
export default defineConfig({
  test: {
    coverage: {
      // ✅ Good
      reportsDirectory: './coverage',

      // ❌ Bad
      reportsDirectory: '/c/project/coverage'
    }
  }
});

マルチプラットフォーム対応のテスト戦略

1. CI/CD の設定

CI/CD で複数のプラットフォームを対象にテストします。

# .github/workflows/test.yml
name: Tests
on: [push, pull_request]

jobs:
  test:
    strategy:
      matrix:
        os: [ubuntu-latest, windows-latest, macos-latest]
        node: [18, 20, 22]
    runs-on: ${{ matrix.os }}

    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ matrix.node }}

      - run: npm ci
      - run: npm test
      - run: npm run test:e2e
        if: matrix.os == 'ubuntu-latest'  # Run E2E on Linux only
2. シェル固有のテストセットアップ

必要に応じて、シェル固有のセットアップを作成します。

// tests/setup.js
import { detectShell } from './helpers/shell-detect.js';

const shell = detectShell();

// Apply shell-specific configuration
if (shell.type === 'mingw') {
  console.log('Running in Git Bash/MINGW environment');
  // Apply MINGW-specific test setup
  process.env.FORCE_COLOR = '1'; // Enable colors in Git Bash
}

// Standard setup continues...
3. パスに依存しないテストユーティリティ

すべてのプラットフォームで動作するテストユーティリティを作成します。

// tests/helpers/test-utils.js
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';

// Get __dirname equivalent in ESM
export function getCurrentDir(importMetaUrl) {
  return dirname(fileURLToPath(importMetaUrl));
}

// Cross-platform path joining
export function testPath(...segments) {
  return path.join(...segments).replace(/\\/g, '/');
}

// Usage in test file:
// const __dirname = getCurrentDir(import.meta.url);
// const fixturePath = testPath(__dirname, 'fixtures', 'data.json');

クイックリファレンス

シェルの検出コマンド
# Check if running in Git Bash
echo $MSYSTEM           # MINGW64, MINGW32, or empty

# Check OS type
uname -s               # MINGW64_NT-* for Git Bash

# Check platform in Node
node -p process.platform  # win32 on Windows
パス変換の簡単な修正方法
# Disable for single command
MSYS_NO_PATHCONV=1 vitest run

# Disable for session
export MSYS_NO_PATHCONV=1

# Convert path manually
cygpath -u "C:\path"    # Windows → Unix
cygpath -w "/c/path"    # Unix → Windows
推奨されるテスト実行方法(Windows の Git Bash)
# ✅ Best - Use npm scripts
npm test
npm run test:e2e

# ✅ Good - With path conversion disabled
MSYS_NO_PATHCONV=1 vitest run

# ⚠️ Caution - Direct vitest command may have issues
vitest run  # May encounter path conversion issues

リソース

まとめ

Git Bash を使用して Windows でテストを実行する場合:

  1. すべてのテスト実行に npm スクリプトを使用する(最も信頼性が高い方法です)
  2. 設定とインポートでは相対パスを使用する
  3. 必要に応じて、条件付きセットアップのためにシェル環境を検出する
  4. 問題が発生した場合は、パス変換を無効にする(MSYS_NO_PATHCONV=1)
  5. CI/CD で複数のプラットフォームをテストし、プラットフォーム固有の問題を検出する
  6. テストファイルでは、/c/ または C:\ で始まる絶対パスを使用しない
  7. プログラムでパスを構築するには、path.join() を使用する

これらのプラクティスに従うことで、Windows コマンドプロンプト、PowerShell、Git Bash、Unix 系環境でテストを安定して実行できます。

コメント