Test Runner Hook - Hooks
Automatically run relevant tests when code changes are detected, with intelligent test selection and parallel execution.
Open the source and read safety notes before installing.
Schema details
- Install type
- cli
- Reading time
- 4 min
- Difficulty score
- 0
- Troubleshooting
- Yes
- Breaking changes
- No
- 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 0Full 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
- Create hooks directory: mkdir -p .claude/hooks
- Create hook file: touch .claude/hooks/test-runner-hook.sh
- Make executable: chmod +x .claude/hooks/test-runner-hook.sh
- Add configuration from Hook Configuration section above to .claude/settings.json or ~/.claude/settings.json
- 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.
- Features
- Use Cases
- Installation
- Config paths
- Requirements
- Hook Configuration
- Hook Script
- Examples
- Test Runner Hook Script
- Hook Configuration
- Enhanced Test Runner with Parallel Execution
- Test Runner with Smart Retry for Flaky Tests
- Test Runner Hook Configuration Example
- Troubleshooting
- Tests run on every file save slowing down development
- Jest testPathPattern not finding related tests
Source citations
Signals
Loading live community signals…
A short, calm digest of reviewed Claude resources. Unsubscribe any time.