Skip to main content
hooksSource-backedReview first Safety Privacy

Test Runner Hook - Hooks

Automatically run relevant tests when code changes are detected, with intelligent test selection and parallel execution.

by JSONbored·added 2025-09-16·
HarnessClaude Code
Trigger:PostToolUse
Review first review before installing

Open the source and read safety notes before installing.

Citation facts

Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.

Source URLs
https://code.claude.com/docs/en/hooks, https://github.com/JSONbored/awesome-claude/blob/main/content/hooks/test-runner-hook.mdx
Safety notes
Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.
Privacy notes
Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.
Author
JSONbored
Claim status
unclaimed
Last verified
2025-09-16

Decision playbook

Review trust signals before you adopt

Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.

Compare context
Selected

0

Current score

78

Baseline

Delta

No baseline selected

No major trust-signal divergence detected in the current selection.

Source and provenance checks

Complete

Confirm ownership and provenance before trusting install instructions.

  • Source link availableRequired

    Open the canonical repository and verify ownership.

    Done
  • Source provenance statusRequired

    Marked as source-backed.

    Done
  • Metadata reviewed

    Registry metadata indicates a reviewed listing.

    Done

Safety and privacy checks

Complete

Validate risk disclosures before installation or API wiring.

  • Safety notes presentRequired

    Review the listed safety guidance before running commands.

    Done
  • Privacy notes presentRequired

    Review data handling notes before connecting accounts or secrets.

    Done
  • Trust level risk gateRequired

    Trust level does not block evaluation.

    Done

Package and install checks

Needs review

Check package metadata and artifact integrity signals.

  • Install payload available

    Install or copy payload is available for review.

    Done
  • Package verification flag

    No package verification flag provided.

    Pending
  • Checksum metadata

    No checksum provided for downloaded artifact.

    Pending

Compare-driven decision checks

Needs review

Use compare context to validate trade-offs before adoption.

  • Compare tray has multiple entries

    Add at least one more entry to compare trust differences.

    Pending
  • Baseline comparison available

    No baseline peer selected yet.

    Pending
  • Diverging trust signals identified

    No major trust-signal divergence found.

    Pending

Setup at a glance

CLI install

Copy-ready — paste the snippet to get started.

Install command

Provided

Config snippet

Provided

Copy snippet

Provided

Prerequisites

None

Platforms

1 listed

Difficulty

0/100

Adoption plan

Balanced adoption plan

Current risk score 16/100. Use staged verification before broader rollout.

Risk 16

Pre-adoption checks

Validate source and review signals before any execution.

  • Confirm source provenanceRequired

    Source URL/provenance metadata is present.

    Done
  • Confirm metadata review state

    Listing has review metadata.

    Done
  • Verify install payload

    Install/config payload exists and can be inspected.

    Done

Security checks

Confirm safety, privacy, and package integrity signals.

  • Review safety notesRequired

    Safety notes are present.

    Done
  • Review privacy notesRequired

    Privacy notes are present.

    Done
  • Verify package integrity metadata

    No package verification/checksum metadata.

    Pending

Rollout

Adopt in controlled steps based on the selected plan.

  • Run in isolated sandbox firstRequired

    Use a constrained sandbox and observe behavior across multiple tasks.

    Pending
  • Roll out graduallyRequired

    Roll out to a small cohort before wider usage.

    Pending
  • Set monitoring and fallback

    Define rollback path and monitor errors after adoption.

    Pending

Evidence readiness

Evidence readiness matrix · balanced

Required evidence gates are covered (5/6 signals complete).

Risk 15

Source provenance

Present

Source repository/provenance is listed.

Required in this preset

Metadata review

Present

Review metadata is present.

Required in this preset

Safety notes

Present

Safety notes are present.

Required in this preset

Privacy notes

Present

Privacy notes are present.

Optional in this preset

Package integrity

Missing

Package integrity metadata is missing.

Optional in this preset

Install payload

Present

Install payload is available.

Required in this preset

Required evidence gates are covered for this preset.

Decision timeline

Decision timeline · balanced

5/6 steps complete with no blocking gaps for this preset.

Risk 14

triage

Confirm source provenanceRequired

Source/provenance metadata is available.

Done

triage

Check metadata review statusRequired

Review metadata is available.

Done

verify

Review safety notesRequired

Safety notes are available.

Done

verify

Review privacy notes

Privacy notes are available.

Done

verify

Validate package integrity metadata

Package integrity metadata is missing.

Pending

rollout

Verify install payload and commandsRequired

Install payload is available.

Done

No required blockers for this timeline preset.

Safety & privacy surface

Safety & privacy surface

1 safety and 1 privacy notes across 2 risk areas. Review closely: credentials & tokens, permissions & scopes.

2 areas
  • SafetyPermissions & scopesRuns automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.
  • PrivacyCredentials & tokensReceives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.

Safety notes

  • Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.

Privacy notes

  • Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.

Schema details

Install type
cli
Reading time
4 min
Difficulty score
0
Troubleshooting
Yes
Breaking changes
No
Skill and platform metadata
Retrieval sources
https://code.claude.com/docs/en/hooks
Runtime and command metadata
Trigger
PostToolUse
Script language
bash
Script body
#!/usr/bin/env bash

# Read the tool input from stdin
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')

if [ -z "$FILE_PATH" ]; then
  exit 0
fi

echo "🧪 Running tests for $FILE_PATH..."

# Get file extension and directory
EXT="${FILE_PATH##*.}"
DIR=$(dirname "$FILE_PATH")

# Find and run relevant tests based on file type
case "$EXT" in
  js|jsx|ts|tsx)
    # JavaScript/TypeScript files
    if [ -f "package.json" ]; then
      if command -v npm &> /dev/null && npm list jest &> /dev/null; then
        echo "Running Jest tests..."
        npm test -- --testPathPattern="$FILE_PATH" --passWithNoTests 2>/dev/null
      elif command -v npm &> /dev/null && npm list vitest &> /dev/null; then
        echo "Running Vitest tests..."
        npx vitest run "$FILE_PATH" 2>/dev/null
      fi
    fi
    ;;
  py)
    # Python files
    if command -v pytest &> /dev/null; then
      echo "Running pytest..."
      pytest "${FILE_PATH%.*}_test.py" "${DIR}/test_*.py" 2>/dev/null || echo "No Python tests found"
    elif command -v python &> /dev/null; then
      echo "Running Python unittest..."
      python -m unittest discover -s "$DIR" -p "*test*.py" 2>/dev/null || echo "No Python tests found"
    fi
    ;;
  go)
    # Go files
    if command -v go &> /dev/null; then
      echo "Running Go tests..."
      go test "${DIR}/..." 2>/dev/null || echo "No Go tests found"
    fi
    ;;
  java)
    # Java files
    if command -v mvn &> /dev/null && [ -f "pom.xml" ]; then
      echo "Running Maven tests..."
      mvn test 2>/dev/null
    elif command -v gradle &> /dev/null && [ -f "build.gradle" ]; then
      echo "Running Gradle tests..."
      gradle test 2>/dev/null
    fi
    ;;
esac

echo "✅ Test execution completed for $FILE_PATH" >&2
exit 0
Full copyable content
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/code-test-runner-hook.sh",
      "matchers": [
        "write",
        "edit",
        "multiedit"
      ]
    }
  }
}

About this resource

Features

  • Intelligent test selection based on code changes including change detection (automatic test selection based on code changes, file change detection with file monitoring, dependency analysis with dependency mapping, test discovery with test identification), selection optimization (selection performance with fast selection, selection accuracy with accurate selection, selection efficiency with efficient processing, selection reporting with selection status), selection validation (test selection validation with selection verification, test relevance validation with relevance checking, test dependency validation with dependency verification, test coverage validation with coverage checking), and selection reporting (test selection reporting with selection status, test relevance reporting with relevance status, test dependency reporting with dependency status, selection analytics with selection statistics)
  • Parallel test execution for faster feedback including parallel execution (parallel test execution with concurrent execution, test parallelization with test distribution, execution optimization with performance improvement, execution reporting with execution status), execution management (execution configuration with execution settings, execution customization with custom execution, execution monitoring with execution tracking, execution updates with execution updates), execution optimization (execution performance optimization with performance improvement, execution reliability optimization with reliability improvement, execution efficiency optimization with efficiency improvement, execution analytics with execution statistics), and execution reporting (parallel execution reporting with execution status, test distribution reporting with distribution status, execution performance reporting with performance status, execution analytics with execution statistics)
  • Support for multiple testing frameworks including framework detection (testing framework detection with framework identification, language detection with language identification, framework configuration detection with config detection, framework version validation with version checking), framework management (framework configuration management with config settings, framework version management with version settings, framework integration with framework support, framework analytics with framework metrics), framework optimization (framework performance optimization with performance improvement, framework reliability optimization with reliability improvement, framework compatibility optimization with compatibility improvement, framework analytics with framework statistics), and framework reporting (framework detection reporting with detection status, framework configuration reporting with config status, framework validation reporting with validation status, framework analytics with framework statistics)
  • Fail-fast mode for quick feedback including fail-fast execution (fail-fast test execution with immediate failure detection, failure detection with failure identification, failure reporting with failure status, failure handling with failure management), fail-fast management (fail-fast configuration with fail-fast settings, fail-fast customization with custom fail-fast, fail-fast monitoring with fail-fast tracking, fail-fast updates with fail-fast updates), fail-fast optimization (fail-fast performance optimization with performance improvement, fail-fast accuracy optimization with accuracy improvement, fail-fast efficiency optimization with efficiency improvement, fail-fast analytics with fail-fast statistics), and fail-fast reporting (fail-fast execution reporting with execution status, failure detection reporting with detection status, failure reporting with failure status, fail-fast analytics with fail-fast statistics)
  • Smart retry for flaky tests including retry execution (smart test retry with intelligent retry logic, flaky test detection with flaky test identification, retry strategy with retry configuration, retry reporting with retry status), retry management (retry configuration with retry settings, retry customization with custom retry, retry monitoring with retry tracking, retry updates with retry updates), retry optimization (retry performance optimization with performance improvement, retry accuracy optimization with accuracy improvement, retry efficiency optimization with efficiency improvement, retry analytics with retry statistics), and retry reporting (smart retry reporting with retry status, flaky test detection reporting with detection status, retry strategy reporting with strategy status, retry analytics with retry statistics)
  • Impact analysis and dependency mapping including impact analysis (code change impact analysis with impact identification, dependency mapping with dependency tracking, test impact analysis with test impact identification, impact reporting with impact status), impact management (impact configuration with impact settings, impact customization with custom impact, impact monitoring with impact tracking, impact updates with impact updates), impact optimization (impact performance optimization with performance improvement, impact accuracy optimization with accuracy improvement, impact efficiency optimization with efficiency improvement, impact analytics with impact statistics), and impact reporting (impact analysis reporting with analysis status, dependency mapping reporting with mapping status, test impact reporting with impact status, impact analytics with impact statistics)
  • Test execution optimization including execution optimization (test execution optimization with performance improvement, test parallelization with test distribution, test caching with test result caching, test reporting with test status), optimization management (optimization configuration with optimization settings, optimization customization with custom optimization, optimization monitoring with optimization tracking, optimization updates with optimization updates), optimization validation (optimization performance validation with performance verification, optimization accuracy validation with accuracy checking, optimization efficiency validation with efficiency checking, optimization analytics with optimization statistics), and optimization reporting (execution optimization reporting with optimization status, test parallelization reporting with parallelization status, test caching reporting with caching status, optimization analytics with optimization statistics)
  • Integration with CI/CD pipelines including CI/CD integration (CI/CD pipeline integration with pipeline support, automated test execution with automatic execution, pipeline configuration with pipeline settings, pipeline reporting with pipeline status), pipeline management (pipeline configuration management with config settings, pipeline customization with custom pipelines, pipeline monitoring with pipeline tracking, pipeline updates with pipeline updates), pipeline optimization (pipeline performance optimization with performance improvement, pipeline reliability optimization with reliability improvement, pipeline efficiency optimization with efficiency improvement, pipeline analytics with pipeline statistics), and pipeline reporting (CI/CD integration reporting with integration status, automated execution reporting with execution status, pipeline configuration reporting with config status, pipeline analytics with pipeline statistics)

Use Cases

  • Automated testing in CI/CD pipelines automatically running tests on code changes, integrating with CI/CD workflows, and providing test execution feedback
  • Real-time test feedback during development automatically running tests on file changes, providing immediate feedback, and enabling rapid iteration
  • Intelligent test selection for large codebases automatically selecting relevant tests based on code changes, reducing test execution time, and improving development efficiency
  • Parallel test execution for faster builds automatically executing tests in parallel, optimizing test execution time, and providing faster feedback
  • Pre-commit test validation automatically running tests before commits, validating code changes, and preventing broken code from being committed
  • Development workflow integration seamlessly integrating test execution into development workflows without manual test runs or test quality validation

Installation

  1. Create hooks directory: mkdir -p .claude/hooks
  2. Create hook file: touch .claude/hooks/test-runner-hook.sh
  3. Make executable: chmod +x .claude/hooks/test-runner-hook.sh
  4. Add configuration from Hook Configuration section above to .claude/settings.json or ~/.claude/settings.json
  5. Alternative: Use the interactive /hooks command in Claude Code

Config paths

  • Local (not committed): .claude/settings.local.json
  • User settings (global): ~/.claude/settings.json
  • Project-wide (committed): .claude/settings.json

Requirements

  • Claude Code CLI installed
  • Project directory initialized
  • Bash shell available
  • Testing framework installed (Jest, Vitest, pytest, Go test, Maven/Gradle)
  • jq (optional, for JSON parsing of tool input)
  • pytest-xdist (optional, for pytest parallel execution)

Hook Configuration

{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/code-test-runner-hook.sh",
      "matchers": ["write", "edit", "multiedit"]
    }
  }
}

Hook Script

#!/usr/bin/env bash

# Read the tool input from stdin
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')

if [ -z "$FILE_PATH" ]; then
  exit 0
fi

echo "🧪 Running tests for $FILE_PATH..."

# Get file extension and directory
EXT="${FILE_PATH##*.}"
DIR=$(dirname "$FILE_PATH")

# Find and run relevant tests based on file type
case "$EXT" in
  js|jsx|ts|tsx)
    # JavaScript/TypeScript files
    if [ -f "package.json" ]; then
      if command -v npm &> /dev/null && npm list jest &> /dev/null; then
        echo "Running Jest tests..."
        npm test -- --testPathPattern="$FILE_PATH" --passWithNoTests 2>/dev/null
      elif command -v npm &> /dev/null && npm list vitest &> /dev/null; then
        echo "Running Vitest tests..."
        npx vitest run "$FILE_PATH" 2>/dev/null
      fi
    fi
    ;;
  py)
    # Python files
    if command -v pytest &> /dev/null; then
      echo "Running pytest..."
      pytest "${FILE_PATH%.*}_test.py" "${DIR}/test_*.py" 2>/dev/null || echo "No Python tests found"
    elif command -v python &> /dev/null; then
      echo "Running Python unittest..."
      python -m unittest discover -s "$DIR" -p "*test*.py" 2>/dev/null || echo "No Python tests found"
    fi
    ;;
  go)
    # Go files
    if command -v go &> /dev/null; then
      echo "Running Go tests..."
      go test "${DIR}/..." 2>/dev/null || echo "No Go tests found"
    fi
    ;;
  java)
    # Java files
    if command -v mvn &> /dev/null && [ -f "pom.xml" ]; then
      echo "Running Maven tests..."
      mvn test 2>/dev/null
    elif command -v gradle &> /dev/null && [ -f "build.gradle" ]; then
      echo "Running Gradle tests..."
      gradle test 2>/dev/null
    fi
    ;;
esac

echo "✅ Test execution completed for $FILE_PATH" >&2
exit 0

Examples

Test Runner Hook Script

Complete hook script that automatically runs relevant tests when code changes are detected

#!/usr/bin/env bash
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if [ -z "$FILE_PATH" ]; then
  exit 0
fi
echo "🧪 Running tests for $FILE_PATH..."
EXT="${FILE_PATH##*.}"
DIR=$(dirname "$FILE_PATH")
case "$EXT" in
  js|jsx|ts|tsx)
    if [ -f "package.json" ]; then
      if command -v npm &> /dev/null && npm list jest &> /dev/null; then
        echo "Running Jest tests..."
        npm test -- --findRelatedTests "$FILE_PATH" --passWithNoTests 2>/dev/null
      elif command -v npm &> /dev/null && npm list vitest &> /dev/null; then
        echo "Running Vitest tests..."
        npx vitest run "$FILE_PATH" 2>/dev/null
      fi
    fi
    ;;
  py)
    if command -v pytest &> /dev/null; then
      echo "Running pytest..."
      pytest "${FILE_PATH%.*}_test.py" "${DIR}/test_*.py" 2>/dev/null || echo "No Python tests found"
    elif command -v python &> /dev/null; then
      echo "Running Python unittest..."
      python -m unittest discover -s "$DIR" -p "*test*.py" 2>/dev/null || echo "No Python tests found"
    fi
    ;;
  go)
    if command -v go &> /dev/null; then
      echo "Running Go tests..."
      go test -timeout 30s "${DIR}/..." 2>/dev/null || echo "No Go tests found"
    fi
    ;;
  java)
    if command -v mvn &> /dev/null && [ -f "pom.xml" ]; then
      echo "Running Maven tests..."
      mvn test 2>/dev/null
    elif command -v gradle &> /dev/null && [ -f "build.gradle" ]; then
      echo "Running Gradle tests..."
      gradle test 2>/dev/null
    fi
    ;;
esac
echo "✅ Test execution completed for $FILE_PATH" >&2
exit 0

Hook Configuration

Complete hook configuration for .claude/settings.json to enable automatic test execution

{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/test-runner-hook.sh",
      "matchers": ["write", "edit", "multiedit"]
    }
  }
}

Enhanced Test Runner with Parallel Execution

Enhanced hook script with parallel test execution, test file filtering, and fail-fast mode

#!/usr/bin/env bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if [ -z "$FILE_PATH" ]; then
  exit 0
fi
if [[ "$FILE_PATH" == *test* ]] || [[ "$FILE_PATH" == *spec* ]]; then
  exit 0
fi
echo "🧪 Running tests for $FILE_PATH..."
EXT="${FILE_PATH##*.}"
DIR=$(dirname "$FILE_PATH")
case "$EXT" in
  js|jsx|ts|tsx)
    if [ -f "package.json" ]; then
      if npm list jest &> /dev/null; then
        echo "Running Jest tests with parallel execution..."
        npm test -- --findRelatedTests "$FILE_PATH" --maxWorkers=4 --passWithNoTests 2>/dev/null
      elif npm list vitest &> /dev/null; then
        echo "Running Vitest tests with parallel execution..."
        npx vitest run "$FILE_PATH" --max-workers=4 2>/dev/null
      fi
    fi
    ;;
  py)
    if command -v pytest &> /dev/null; then
      echo "Running pytest with parallel execution..."
      pytest "${FILE_PATH%.*}_test.py" "${DIR}/test_*.py" -n auto --maxfail=1 2>/dev/null || echo "No Python tests found"
    fi
    ;;
  go)
    if command -v go &> /dev/null; then
      echo "Running Go tests with parallel execution..."
      go test -timeout 30s -parallel 4 "${DIR}/..." 2>/dev/null || echo "No Go tests found"
    fi
    ;;
esac
echo "✅ Test execution completed for $FILE_PATH" >&2
exit 0

Test Runner with Smart Retry for Flaky Tests

Enhanced hook script with smart retry logic for handling flaky tests

#!/usr/bin/env bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if [ -z "$FILE_PATH" ]; then
  exit 0
fi
echo "🧪 Running tests for $FILE_PATH with smart retry..."
EXT="${FILE_PATH##*.}"
DIR=$(dirname "$FILE_PATH")
MAX_RETRIES=3
RETRY_COUNT=0
case "$EXT" in
  js|jsx|ts|tsx)
    if [ -f "package.json" ]; then
      if npm list jest &> /dev/null; then
        while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
          if npm test -- --findRelatedTests "$FILE_PATH" --passWithNoTests 2>/dev/null; then
            echo "✅ Tests passed on attempt $((RETRY_COUNT + 1))"
            exit 0
          else
            RETRY_COUNT=$((RETRY_COUNT + 1))
            if [ $RETRY_COUNT -lt $MAX_RETRIES ]; then
              echo "⚠️ Test failed, retrying (attempt $((RETRY_COUNT + 1))/$MAX_RETRIES)..."
              sleep 1
            fi
          fi
        done
        echo "❌ Tests failed after $MAX_RETRIES attempts"
        exit 1
      fi
    fi
    ;;
  py)
    if command -v pytest &> /dev/null; then
      while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
        if pytest "${FILE_PATH%.*}_test.py" "${DIR}/test_*.py" --maxfail=1 2>/dev/null; then
          echo "✅ Tests passed on attempt $((RETRY_COUNT + 1))"
          exit 0
        else
          RETRY_COUNT=$((RETRY_COUNT + 1))
          if [ $RETRY_COUNT -lt $MAX_RETRIES ]; then
            echo "⚠️ Test failed, retrying (attempt $((RETRY_COUNT + 1))/$MAX_RETRIES)..."
            sleep 1
          fi
        fi
      done
      echo "❌ Tests failed after $MAX_RETRIES attempts"
      exit 1
    fi
    ;;
esac
echo "✅ Test execution completed for $FILE_PATH" >&2
exit 0

Test Runner Hook Configuration Example

Example test runner hook configuration for customizing test execution behavior

{
  "test_runner": {
    "enabled": true,
    "parallel_execution": true,
    "max_workers": 4,
    "fail_fast": true,
    "max_failures": 1,
    "retry_flaky_tests": true,
    "max_retries": 3,
    "skip_test_files": true,
    "frameworks": {
      "jest": {
        "command": "npm test -- --findRelatedTests",
        "parallel": "--maxWorkers=4",
        "fail_fast": "--bail"
      },
      "vitest": {
        "command": "npx vitest run",
        "parallel": "--max-workers=4",
        "fail_fast": "--bail"
      },
      "pytest": {
        "command": "pytest",
        "parallel": "-n auto",
        "fail_fast": "--maxfail=1"
      },
      "go": {
        "command": "go test",
        "parallel": "-parallel 4",
        "timeout": "-timeout 30s"
      }
    },
    "file_extensions": ["js", "jsx", "ts", "tsx", "py", "go", "java"],
    "exclude_patterns": [
      "**/node_modules/**",
      "**/vendor/**",
      "**/__pycache__/**"
    ]
  }
}

Troubleshooting

Tests run on every file save slowing down development

Add file extension filter or test file detection: if [[ "$FILE_PATH" == *test* ]] || [[ "$FILE_PATH" == *spec* ]]; then exit 0; fi to skip running tests when editing test files themselves. Configure matchers to exclude test files. Use debouncing for rapid file changes.

Jest testPathPattern not finding related tests

Pattern matches test file paths not source. Use --findRelatedTests instead: npm test -- --findRelatedTests="$FILE_PATH" which finds tests importing the changed file through dependency graph. Verify Jest configuration. Check test file naming conventions.

Hook runs tests twice with both Jest and Vitest

Detection uses npm list jest which may find both. Add explicit priority: if npm list jest &> /dev/null; then run_jest; exit 0; elif npm list vitest ... to prevent fallthrough. Verify package.json dependencies. Check framework detection logic.

Python tests fail to locate test directory

Hook looks for ${FILE_PATH%.*}_test.py and test_*.py. For pytest, use explicit discovery: pytest --collect-only "$DIR" 2>/dev/null | grep "test session starts" to verify test detection. Check pytest configuration. Verify test file naming conventions.

Go tests timeout on large module changes

Add timeout flag and scope: go test -timeout 30s "${DIR}" 2>/dev/null instead of ${DIR}/... which tests all subpackages. Or use go test -short for quick tests only during development. Verify Go module structure. Check test execution scope.

Parallel test execution causes race conditions

Disable parallel execution for tests with shared state: npm test -- --runInBand for Jest, npx vitest run --no-file-parallelism for Vitest, pytest -n 1 for pytest. Configure test isolation. Verify test dependencies.

Vitest watch mode conflicts with hook execution

Use vitest run instead of vitest to avoid watch mode conflicts. Ensure hook runs in non-interactive mode. Configure Vitest for CI/CD environments. Verify Vitest configuration.

pytest parallel execution requires pytest-xdist

Install pytest-xdist: pip install pytest-xdist. Use pytest -n auto for automatic worker count. Verify pytest-xdist installation. Check pytest configuration for parallel execution settings.

Source citations

Add this badge to your README

Show that Test Runner Hook - Hooks is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.

Listed on HeyClaude
[![Listed on HeyClaude](https://heyclau.de/badge/hooks/test-runner-hook.svg)](https://heyclau.de/entry/hooks/test-runner-hook)

How it compares

Test Runner Hook - Hooks side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.

Field

Automatically run relevant tests when code changes are detected, with intelligent test selection and parallel execution.

Open dossier

A PostToolUse hook that runs the matching test runner for a changed file's language — Jest or Vitest for JS/TS, pytest for Python, go test, or Maven/Gradle for Java — scoped to the edited file.

Open dossier

Automatically runs Playwright E2E tests when test files or page components are modified.

Open dossier

Automated accessibility testing and compliance checking for web applications following WCAG 2.1 and WCAG 2.2 guidelines. This hook automatically runs accessibility scans on HTML files after they are written or edited, using axe-core for comprehensive WCAG compliance testing.

Open dossier
Next steps
Trust
Review statusReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewedReviewedMaintainer reviewed
Package trustPackage not verifiedPackage not verifiedPackage not verifiedPackage not verified
Source provenanceSource-backedSource-backedSource-backedSource-backed
Submitter
Install riskReview firstReview firstReview firstReview first
Notes Safety Privacy Safety Privacy Safety Privacy Safety Privacy
Brand
Categoryhookshookshookshooks
Sourcesource-backedsource-backedsource-backedsource-backed
AuthorJSONboredJSONboredJSONboredJSONbored
Added2025-09-162025-09-162025-09-192025-09-19
Platforms
Claude Code
Claude Code
Claude Code
Claude Code
Source repo
Safety notesRuns automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.Runs your project's test command automatically after each edit; tests execute arbitrary project code, so enable this only in a trusted repo and expect it to run frequently. The script invokes whichever runner it detects (npm test, npx vitest, pytest, go test, mvn/gradle); make sure the right one is installed so it does not run an unexpected command.Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.Runs automatically on its configured Claude Code hook event and executes shell logic that can read, modify, or delete files in your project (and may run builds, installs, or network calls); review the script and scope it to expected paths before enabling.
Privacy notesReceives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.Runs locally and prints test output to the hook; that output can include file paths, test names, and any data your tests log.Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.Receives Claude Code hook input (session metadata, file paths, and tool output) and reads local project files; review what the script logs or forwards to external services and keep credentials out of its output.
Prerequisites— none listed— none listed— none listed— none listed
Install
mkdir -p .claude/hooks && touch .claude/hooks/test-runner-hook.sh && chmod +x .claude/hooks/test-runner-hook.sh
mkdir -p .claude/hooks && touch .claude/hooks/code-test-runner-hook.sh && chmod +x .claude/hooks/code-test-runner-hook.sh
mkdir -p .claude/hooks && touch .claude/hooks/playwright-test-runner.sh && chmod +x .claude/hooks/playwright-test-runner.sh
mkdir -p .claude/hooks && touch .claude/hooks/accessibility-checker.sh && chmod +x .claude/hooks/accessibility-checker.sh
Config
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/code-test-runner-hook.sh",
      "matchers": [
        "write",
        "edit",
        "multiedit"
      ]
    }
  }
}
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/code-test-runner-hook.sh",
      "matchers": [
        "write",
        "edit",
        "multiedit"
      ]
    }
  }
}
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/playwright-test-runner.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}
{
  "hooks": {
    "postToolUse": {
      "script": "./.claude/hooks/accessibility-checker.sh",
      "matchers": [
        "write",
        "edit"
      ]
    }
  }
}
Citations
ClaimUnclaimedUnclaimedUnclaimedUnclaimed
Open 4 picks in the interactive comparison tool

Related guides

Signals

Loading live community signals…

More like this, weekly

A short, calm digest of reviewed Claude resources. Unsubscribe any time.