Install command
Provided
Automatically updates Jest snapshots when component files are modified significantly.
Open the source and read safety notes before installing.
Source-backed facts for citing this resource, derived directly from the registry — also available as plain text for AI assistants.
Decision playbook
Signals are present but mixed. Use the checklist below to confirm the source and operational safety for your environment.
0
78
—
No baseline selected
No major trust-signal divergence detected in the current selection.
Confirm ownership and provenance before trusting install instructions.
Source link availableRequired
Open the canonical repository and verify ownership.
Source provenance statusRequired
Marked as source-backed.
Metadata reviewed
Registry metadata indicates a reviewed listing.
Validate risk disclosures before installation or API wiring.
Safety notes presentRequired
Review the listed safety guidance before running commands.
Privacy notes presentRequired
Review data handling notes before connecting accounts or secrets.
Trust level risk gateRequired
Trust level does not block evaluation.
Check package metadata and artifact integrity signals.
Install payload available
Install or copy payload is available for review.
Package verification flag
No package verification flag provided.
Checksum metadata
No checksum provided for downloaded artifact.
Use compare context to validate trade-offs before adoption.
Compare tray has multiple entries
Add at least one more entry to compare trust differences.
Baseline comparison available
No baseline peer selected yet.
Diverging trust signals identified
No major trust-signal divergence found.
Setup at a glance
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
Current risk score 16/100. Use staged verification before broader rollout.
Validate source and review signals before any execution.
Confirm source provenanceRequired
Source URL/provenance metadata is present.
Confirm metadata review state
Listing has review metadata.
Verify install payload
Install/config payload exists and can be inspected.
Confirm safety, privacy, and package integrity signals.
Review safety notesRequired
Safety notes are present.
Review privacy notesRequired
Privacy notes are present.
Verify package integrity metadata
No package verification/checksum metadata.
Adopt in controlled steps based on the selected plan.
Run in isolated sandbox firstRequired
Use a constrained sandbox and observe behavior across multiple tasks.
Roll out graduallyRequired
Roll out to a small cohort before wider usage.
Set monitoring and fallback
Define rollback path and monitor errors after adoption.
Evidence readiness
Required evidence gates are covered (5/6 signals complete).
Source repository/provenance is listed.
Required in this preset
Review metadata is present.
Required in this preset
Safety notes are present.
Required in this preset
Privacy notes are present.
Optional in this preset
Package integrity metadata is missing.
Optional in this preset
Install payload is available.
Required in this preset
Required evidence gates are covered for this preset.
Decision timeline
5/6 steps complete with no blocking gaps for this preset.
triage
Source/provenance metadata is available.
triage
Review metadata is available.
verify
Safety notes are available.
verify
Privacy notes are available.
verify
Package integrity metadata is missing.
rollout
Install payload is available.
No required blockers for this timeline preset.
Safety & privacy surface
1 safety and 1 privacy notes across 2 risk areas. Review closely: credentials & tokens, permissions & scopes.
#!/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
# Check if this is a component file that might have Jest snapshots
if [[ "$FILE_PATH" == *.jsx ]] || [[ "$FILE_PATH" == *.tsx ]] || [[ "$FILE_PATH" == *.js ]] || [[ "$FILE_PATH" == *.ts ]] || [[ "$FILE_PATH" == *.vue ]] || [[ "$FILE_PATH" == *.component.ts ]]; then
echo "📸 Jest Snapshot Management for: $(basename "$FILE_PATH")" >&2
# Initialize counters
SNAPSHOTS_UPDATED=0
TESTS_RUN=0
TESTS_PASSED=0
TESTS_FAILED=0
SNAPSHOT_FILES_FOUND=0
# Function to report snapshot operations
report_snapshot() {
local level="$1"
local message="$2"
case "$level" in
"SUCCESS")
echo "✅ SUCCESS: $message" >&2
;;
"WARNING")
echo "⚠️ WARNING: $message" >&2
;;
"ERROR")
echo "❌ ERROR: $message" >&2
;;
"INFO")
echo "ℹ️ INFO: $message" >&2
;;
"SNAPSHOT")
echo "📸 SNAPSHOT: $message" >&2
SNAPSHOTS_UPDATED=$((SNAPSHOTS_UPDATED + 1))
;;
esac
}
# Extract component information
FILE_NAME="$(basename "$FILE_PATH")"
COMPONENT_NAME="${FILE_NAME%.*}"
FILE_DIR="$(dirname "$FILE_PATH")"
# Check if this is likely a component or test file
if [[ "$FILE_NAME" == *.test.* ]] || [[ "$FILE_NAME" == *.spec.* ]]; then
echo " 🧪 Test file detected - checking for snapshot updates" >&2
else
echo " 🔧 Component file detected - looking for related tests" >&2
fi
# Check if Jest is available
if ! command -v npx &> /dev/null; then
report_snapshot "ERROR" "npx not available - cannot run Jest"
exit 1
fi
# Check if Jest is configured in the project
JEST_CONFIG_FOUND=false
if [ -f "package.json" ]; then
if grep -q '"jest"' package.json 2>/dev/null || grep -q '"@jest"' package.json 2>/dev/null; then
JEST_CONFIG_FOUND=true
echo " 📋 Jest configuration found in package.json" >&2
fi
fi
if [ -f "jest.config.js" ] || [ -f "jest.config.ts" ] || [ -f "jest.config.json" ]; then
JEST_CONFIG_FOUND=true
echo " 📋 Jest configuration file found" >&2
fi
if [ "$JEST_CONFIG_FOUND" = false ]; then
report_snapshot "WARNING" "No Jest configuration found - snapshots may not be available"
exit 0
fi
# 1. Find existing snapshot files
echo "🔍 Searching for existing snapshot files..." >&2
SNAPSHOT_DIRS=("__snapshots__" "snapshots" "__tests__/__snapshots__" "tests/__snapshots__")
SNAPSHOT_FILES=()
for dir in "${SNAPSHOT_DIRS[@]}"; do
if [ -d "$FILE_DIR/$dir" ]; then
while IFS= read -r -d '' file; do
SNAPSHOT_FILES+=("$file")
done < <(find "$FILE_DIR/$dir" -name "*.snap" -print0 2>/dev/null)
fi
done
# Also check for snapshots in test directories
while IFS= read -r -d '' file; do
SNAPSHOT_FILES+=("$file")
done < <(find . -name "*.snap" -path "*$COMPONENT_NAME*" -print0 2>/dev/null)
SNAPSHOT_FILES_FOUND=${#SNAPSHOT_FILES[@]}
if [ "$SNAPSHOT_FILES_FOUND" -gt 0 ]; then
echo " 📁 Found $SNAPSHOT_FILES_FOUND snapshot files related to this component" >&2
for snapshot in "${SNAPSHOT_FILES[@]}"; do
echo " - $(basename "$snapshot")" >&2
done
else
echo " ℹ️ No existing snapshot files found for this component" >&2
fi
# 2. Find test files for this component
echo "🧪 Locating test files..." >&2
TEST_PATTERNS=(
"${COMPONENT_NAME}.test.*"
"${COMPONENT_NAME}.spec.*"
"*${COMPONENT_NAME}*.test.*"
"*${COMPONENT_NAME}*.spec.*"
)
TEST_FILES=()
for pattern in "${TEST_PATTERNS[@]}"; do
while IFS= read -r -d '' file; do
TEST_FILES+=("$file")
done < <(find . -name "$pattern" -print0 2>/dev/null)
done
TEST_FILES_COUNT=${#TEST_FILES[@]}
if [ "$TEST_FILES_COUNT" -gt 0 ]; then
echo " 🎯 Found $TEST_FILES_COUNT test files" >&2
for test_file in "${TEST_FILES[@]}"; do
echo " - $(basename "$test_file")" >&2
done
else
echo " ⚠️ No test files found for component: $COMPONENT_NAME" >&2
report_snapshot "INFO" "Consider creating tests for better component coverage"
fi
# 3. Check if component file has been significantly modified
echo "📊 Analyzing component changes..." >&2
# Check git status to see if file was modified
if command -v git &> /dev/null && git rev-parse --git-dir > /dev/null 2>&1; then
if git status --porcelain "$FILE_PATH" | grep -q '^.M'; then
echo " 🔄 Component has been modified since last commit" >&2
# Get the diff to understand the scope of changes
LINES_CHANGED=$(git diff "$FILE_PATH" 2>/dev/null | grep -c '^[+-]' || echo "0")
if [ "$LINES_CHANGED" -gt 10 ]; then
echo " 📈 Significant changes detected ($LINES_CHANGED lines modified)" >&2
SHOULD_UPDATE_SNAPSHOTS=true
else
echo " 📝 Minor changes detected ($LINES_CHANGED lines modified)" >&2
SHOULD_UPDATE_SNAPSHOTS=false
fi
else
echo " ✅ Component file is clean (no unsaved changes)" >&2
SHOULD_UPDATE_SNAPSHOTS=false
fi
else
echo " ℹ️ Not in a git repository - assuming snapshots should be checked" >&2
SHOULD_UPDATE_SNAPSHOTS=true
fi
# 4. Run tests and update snapshots if needed
if [ "$TEST_FILES_COUNT" -gt 0 ]; then
echo "🧪 Running tests for component..." >&2
# Determine the test command
TEST_COMMAND="npm test"
if [ -f "yarn.lock" ]; then
TEST_COMMAND="yarn test"
elif [ -f "pnpm-lock.yaml" ]; then
TEST_COMMAND="pnpm test"
fi
# Create test patterns for Jest
TEST_PATTERN="$COMPONENT_NAME"
echo " 🚀 Running: $TEST_COMMAND -- --testNamePattern='$TEST_PATTERN' --coverage=false --watchAll=false" >&2
# Run tests without updating snapshots first
TEST_OUTPUT_FILE="/tmp/jest_output_$$"
if $TEST_COMMAND -- --testNamePattern="$TEST_PATTERN" --coverage=false --watchAll=false --verbose=false > "$TEST_OUTPUT_FILE" 2>&1; then
TESTS_PASSED=$(grep -c 'PASS' "$TEST_OUTPUT_FILE" 2>/dev/null || echo "0")
report_snapshot "SUCCESS" "Tests passed ($TESTS_PASSED test suites)"
# Check if snapshots are outdated
if grep -q 'snapshot.*failed' "$TEST_OUTPUT_FILE" 2>/dev/null || grep -q 'snapshot.*obsolete' "$TEST_OUTPUT_FILE" 2>/dev/null; then
echo " 📸 Outdated snapshots detected" >&2
SHOULD_UPDATE_SNAPSHOTS=true
fi
else
TESTS_FAILED=$(grep -c 'FAIL' "$TEST_OUTPUT_FILE" 2>/dev/null || echo "1")
echo " ❌ Tests failed ($TESTS_FAILED test suites) - checking for snapshot issues" >&2
# Check if failures are due to snapshot mismatches
if grep -q 'Snapshot.*differ' "$TEST_OUTPUT_FILE" 2>/dev/null; then
echo " 📸 Snapshot mismatches detected - snapshots may need updating" >&2
SHOULD_UPDATE_SNAPSHOTS=true
else
report_snapshot "ERROR" "Tests failing for reasons other than snapshots"
echo " 📝 Test output summary:" >&2
tail -10 "$TEST_OUTPUT_FILE" | while read line; do
echo " $line" >&2
done
fi
fi
rm -f "$TEST_OUTPUT_FILE"
fi
# 5. Update snapshots if needed
if [ "$SHOULD_UPDATE_SNAPSHOTS" = true ] && [ "$TEST_FILES_COUNT" -gt 0 ]; then
echo "📸 Updating Jest snapshots..." >&2
# Run with snapshot update flag
UPDATE_OUTPUT_FILE="/tmp/jest_update_$$"
if $TEST_COMMAND -- --testNamePattern="$TEST_PATTERN" --updateSnapshot --coverage=false --watchAll=false > "$UPDATE_OUTPUT_FILE" 2>&1; then
# Count updated snapshots
SNAPSHOTS_WRITTEN=$(grep -c 'snapshot.*written' "$UPDATE_OUTPUT_FILE" 2>/dev/null || echo "0")
SNAPSHOTS_UPDATED_COUNT=$(grep -c 'snapshot.*updated' "$UPDATE_OUTPUT_FILE" 2>/dev/null || echo "0")
if [ "$SNAPSHOTS_WRITTEN" -gt 0 ] || [ "$SNAPSHOTS_UPDATED_COUNT" -gt 0 ]; then
report_snapshot "SNAPSHOT" "Updated $((SNAPSHOTS_WRITTEN + SNAPSHOTS_UPDATED_COUNT)) snapshots"
# Show which snapshots were affected
grep 'snapshot.*written\|snapshot.*updated' "$UPDATE_OUTPUT_FILE" 2>/dev/null | head -5 | while read line; do
echo " $line" >&2
done
else
report_snapshot "INFO" "Snapshot update completed - no changes needed"
fi
else
report_snapshot "ERROR" "Failed to update snapshots"
echo " 📝 Update error details:" >&2
tail -5 "$UPDATE_OUTPUT_FILE" | while read line; do
echo " $line" >&2
done
fi
rm -f "$UPDATE_OUTPUT_FILE"
else
echo " ℹ️ Snapshot updates not needed at this time" >&2
fi
# 6. Clean up orphaned snapshots
echo "🧹 Checking for orphaned snapshots..." >&2
if [ "$SNAPSHOT_FILES_FOUND" -gt 0 ]; then
# This is a simplified check - in practice, you'd want more sophisticated orphan detection
POTENTIALLY_ORPHANED=0
for snapshot_file in "${SNAPSHOT_FILES[@]}"; do
SNAPSHOT_BASE=$(basename "$snapshot_file" .snap)
# Check if there's a corresponding test or component file
if ! find . -name "*${SNAPSHOT_BASE%.*}*" -type f \( -name "*.test.*" -o -name "*.spec.*" \) 2>/dev/null | head -1 | grep -q .; then
POTENTIALLY_ORPHANED=$((POTENTIALLY_ORPHANED + 1))
fi
done
if [ "$POTENTIALLY_ORPHANED" -gt 0 ]; then
report_snapshot "WARNING" "$POTENTIALLY_ORPHANED potentially orphaned snapshot files detected"
echo " 💡 Run 'npm test -- --updateSnapshot' to clean up unused snapshots" >&2
else
echo " ✅ No orphaned snapshots detected" >&2
fi
fi
# 7. Generate summary report
echo "" >&2
echo "📋 Jest Snapshot Management Summary:" >&2
echo "===================================" >&2
echo " 📄 Component: $COMPONENT_NAME" >&2
echo " 🧪 Test files found: $TEST_FILES_COUNT" >&2
echo " 📸 Snapshot files: $SNAPSHOT_FILES_FOUND" >&2
echo " ✅ Tests passed: $TESTS_PASSED" >&2
echo " ❌ Tests failed: $TESTS_FAILED" >&2
echo " 📸 Snapshots updated: $SNAPSHOTS_UPDATED" >&2
if [ "$SNAPSHOTS_UPDATED" -gt 0 ]; then
echo " 🎉 Status: SNAPSHOTS UPDATED - Review changes before committing" >&2
elif [ "$TESTS_FAILED" -gt 0 ]; then
echo " ⚠️ Status: TESTS FAILING - Fix issues before proceeding" >&2
elif [ "$TEST_FILES_COUNT" -eq 0 ]; then
echo " 📝 Status: NO TESTS - Consider adding snapshot tests" >&2
else
echo " ✅ Status: ALL GOOD - Snapshots are up to date" >&2
fi
echo "" >&2
echo "💡 Jest Snapshot Best Practices:" >&2
echo " • Review snapshot changes carefully before committing" >&2
echo " • Keep snapshots small and focused" >&2
echo " • Update snapshots only when UI changes are intentional" >&2
echo " • Use descriptive test names for better snapshot organization" >&2
echo " • Consider using 'toMatchInlineSnapshot' for small snapshots" >&2
echo " • Run 'npm test -- --updateSnapshot' to update all snapshots" >&2
# Exit with error if tests are failing for non-snapshot reasons
if [ "$TESTS_FAILED" -gt 0 ] && [ "$SNAPSHOTS_UPDATED" -eq 0 ]; then
echo "⚠️ Jest tests are failing - please review and fix issues" >&2
exit 1
fi
else
# Not a component file, exit silently
exit 0
fi
exit 0{
"hooks": {
"postToolUse": {
"script": "./.claude/hooks/jest-snapshot-auto-updater.sh",
"matchers": [
"write",
"edit"
]
}
}
}.claude/settings.local.json~/.claude/settings.json.claude/settings.json{
"hooks": {
"postToolUse": {
"script": "./.claude/hooks/jest-snapshot-auto-updater.sh",
"matchers": ["write", "edit"]
}
}
}
#!/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
# Check if this is a component file that might have Jest snapshots
if [[ "$FILE_PATH" == *.jsx ]] || [[ "$FILE_PATH" == *.tsx ]] || [[ "$FILE_PATH" == *.js ]] || [[ "$FILE_PATH" == *.ts ]] || [[ "$FILE_PATH" == *.vue ]] || [[ "$FILE_PATH" == *.component.ts ]]; then
echo "📸 Jest Snapshot Management for: $(basename "$FILE_PATH")" >&2
# Initialize counters
SNAPSHOTS_UPDATED=0
TESTS_RUN=0
TESTS_PASSED=0
TESTS_FAILED=0
SNAPSHOT_FILES_FOUND=0
# Function to report snapshot operations
report_snapshot() {
local level="$1"
local message="$2"
case "$level" in
"SUCCESS")
echo "✅ SUCCESS: $message" >&2
;;
"WARNING")
echo "⚠️ WARNING: $message" >&2
;;
"ERROR")
echo "❌ ERROR: $message" >&2
;;
"INFO")
echo "ℹ️ INFO: $message" >&2
;;
"SNAPSHOT")
echo "📸 SNAPSHOT: $message" >&2
SNAPSHOTS_UPDATED=$((SNAPSHOTS_UPDATED + 1))
;;
esac
}
# Extract component information
FILE_NAME="$(basename "$FILE_PATH")"
COMPONENT_NAME="${FILE_NAME%.*}"
FILE_DIR="$(dirname "$FILE_PATH")"
# Check if this is likely a component or test file
if [[ "$FILE_NAME" == *.test.* ]] || [[ "$FILE_NAME" == *.spec.* ]]; then
echo " 🧪 Test file detected - checking for snapshot updates" >&2
else
echo " 🔧 Component file detected - looking for related tests" >&2
fi
# Check if Jest is available
if ! command -v npx &> /dev/null; then
report_snapshot "ERROR" "npx not available - cannot run Jest"
exit 1
fi
# Check if Jest is configured in the project
JEST_CONFIG_FOUND=false
if [ -f "package.json" ]; then
if grep -q '"jest"' package.json 2>/dev/null || grep -q '"@jest"' package.json 2>/dev/null; then
JEST_CONFIG_FOUND=true
echo " 📋 Jest configuration found in package.json" >&2
fi
fi
if [ -f "jest.config.js" ] || [ -f "jest.config.ts" ] || [ -f "jest.config.json" ]; then
JEST_CONFIG_FOUND=true
echo " 📋 Jest configuration file found" >&2
fi
if [ "$JEST_CONFIG_FOUND" = false ]; then
report_snapshot "WARNING" "No Jest configuration found - snapshots may not be available"
exit 0
fi
# 1. Find existing snapshot files
echo "🔍 Searching for existing snapshot files..." >&2
SNAPSHOT_DIRS=("__snapshots__" "snapshots" "__tests__/__snapshots__" "tests/__snapshots__")
SNAPSHOT_FILES=()
for dir in "${SNAPSHOT_DIRS[@]}"; do
if [ -d "$FILE_DIR/$dir" ]; then
while IFS= read -r -d '' file; do
SNAPSHOT_FILES+=("$file")
done < <(find "$FILE_DIR/$dir" -name "*.snap" -print0 2>/dev/null)
fi
done
# Also check for snapshots in test directories
while IFS= read -r -d '' file; do
SNAPSHOT_FILES+=("$file")
done < <(find . -name "*.snap" -path "*$COMPONENT_NAME*" -print0 2>/dev/null)
SNAPSHOT_FILES_FOUND=${#SNAPSHOT_FILES[@]}
if [ "$SNAPSHOT_FILES_FOUND" -gt 0 ]; then
echo " 📁 Found $SNAPSHOT_FILES_FOUND snapshot files related to this component" >&2
for snapshot in "${SNAPSHOT_FILES[@]}"; do
echo " - $(basename "$snapshot")" >&2
done
else
echo " ℹ️ No existing snapshot files found for this component" >&2
fi
# 2. Find test files for this component
echo "🧪 Locating test files..." >&2
TEST_PATTERNS=(
"${COMPONENT_NAME}.test.*"
"${COMPONENT_NAME}.spec.*"
"*${COMPONENT_NAME}*.test.*"
"*${COMPONENT_NAME}*.spec.*"
)
TEST_FILES=()
for pattern in "${TEST_PATTERNS[@]}"; do
while IFS= read -r -d '' file; do
TEST_FILES+=("$file")
done < <(find . -name "$pattern" -print0 2>/dev/null)
done
TEST_FILES_COUNT=${#TEST_FILES[@]}
if [ "$TEST_FILES_COUNT" -gt 0 ]; then
echo " 🎯 Found $TEST_FILES_COUNT test files" >&2
for test_file in "${TEST_FILES[@]}"; do
echo " - $(basename "$test_file")" >&2
done
else
echo " ⚠️ No test files found for component: $COMPONENT_NAME" >&2
report_snapshot "INFO" "Consider creating tests for better component coverage"
fi
# 3. Check if component file has been significantly modified
echo "📊 Analyzing component changes..." >&2
# Check git status to see if file was modified
if command -v git &> /dev/null && git rev-parse --git-dir > /dev/null 2>&1; then
if git status --porcelain "$FILE_PATH" | grep -q '^.M'; then
echo " 🔄 Component has been modified since last commit" >&2
# Get the diff to understand the scope of changes
LINES_CHANGED=$(git diff "$FILE_PATH" 2>/dev/null | grep -c '^[+-]' || echo "0")
if [ "$LINES_CHANGED" -gt 10 ]; then
echo " 📈 Significant changes detected ($LINES_CHANGED lines modified)" >&2
SHOULD_UPDATE_SNAPSHOTS=true
else
echo " 📝 Minor changes detected ($LINES_CHANGED lines modified)" >&2
SHOULD_UPDATE_SNAPSHOTS=false
fi
else
echo " ✅ Component file is clean (no unsaved changes)" >&2
SHOULD_UPDATE_SNAPSHOTS=false
fi
else
echo " ℹ️ Not in a git repository - assuming snapshots should be checked" >&2
SHOULD_UPDATE_SNAPSHOTS=true
fi
# 4. Run tests and update snapshots if needed
if [ "$TEST_FILES_COUNT" -gt 0 ]; then
echo "🧪 Running tests for component..." >&2
# Determine the test command
TEST_COMMAND="npm test"
if [ -f "yarn.lock" ]; then
TEST_COMMAND="yarn test"
elif [ -f "pnpm-lock.yaml" ]; then
TEST_COMMAND="pnpm test"
fi
# Create test patterns for Jest
TEST_PATTERN="$COMPONENT_NAME"
echo " 🚀 Running: $TEST_COMMAND -- --testNamePattern='$TEST_PATTERN' --coverage=false --watchAll=false" >&2
# Run tests without updating snapshots first
TEST_OUTPUT_FILE="/tmp/jest_output_$$"
if $TEST_COMMAND -- --testNamePattern="$TEST_PATTERN" --coverage=false --watchAll=false --verbose=false > "$TEST_OUTPUT_FILE" 2>&1; then
TESTS_PASSED=$(grep -c 'PASS' "$TEST_OUTPUT_FILE" 2>/dev/null || echo "0")
report_snapshot "SUCCESS" "Tests passed ($TESTS_PASSED test suites)"
# Check if snapshots are outdated
if grep -q 'snapshot.*failed' "$TEST_OUTPUT_FILE" 2>/dev/null || grep -q 'snapshot.*obsolete' "$TEST_OUTPUT_FILE" 2>/dev/null; then
echo " 📸 Outdated snapshots detected" >&2
SHOULD_UPDATE_SNAPSHOTS=true
fi
else
TESTS_FAILED=$(grep -c 'FAIL' "$TEST_OUTPUT_FILE" 2>/dev/null || echo "1")
echo " ❌ Tests failed ($TESTS_FAILED test suites) - checking for snapshot issues" >&2
# Check if failures are due to snapshot mismatches
if grep -q 'Snapshot.*differ' "$TEST_OUTPUT_FILE" 2>/dev/null; then
echo " 📸 Snapshot mismatches detected - snapshots may need updating" >&2
SHOULD_UPDATE_SNAPSHOTS=true
else
report_snapshot "ERROR" "Tests failing for reasons other than snapshots"
echo " 📝 Test output summary:" >&2
tail -10 "$TEST_OUTPUT_FILE" | while read line; do
echo " $line" >&2
done
fi
fi
rm -f "$TEST_OUTPUT_FILE"
fi
# 5. Update snapshots if needed
if [ "$SHOULD_UPDATE_SNAPSHOTS" = true ] && [ "$TEST_FILES_COUNT" -gt 0 ]; then
echo "📸 Updating Jest snapshots..." >&2
# Run with snapshot update flag
UPDATE_OUTPUT_FILE="/tmp/jest_update_$$"
if $TEST_COMMAND -- --testNamePattern="$TEST_PATTERN" --updateSnapshot --coverage=false --watchAll=false > "$UPDATE_OUTPUT_FILE" 2>&1; then
# Count updated snapshots
SNAPSHOTS_WRITTEN=$(grep -c 'snapshot.*written' "$UPDATE_OUTPUT_FILE" 2>/dev/null || echo "0")
SNAPSHOTS_UPDATED_COUNT=$(grep -c 'snapshot.*updated' "$UPDATE_OUTPUT_FILE" 2>/dev/null || echo "0")
if [ "$SNAPSHOTS_WRITTEN" -gt 0 ] || [ "$SNAPSHOTS_UPDATED_COUNT" -gt 0 ]; then
report_snapshot "SNAPSHOT" "Updated $((SNAPSHOTS_WRITTEN + SNAPSHOTS_UPDATED_COUNT)) snapshots"
# Show which snapshots were affected
grep 'snapshot.*written\|snapshot.*updated' "$UPDATE_OUTPUT_FILE" 2>/dev/null | head -5 | while read line; do
echo " $line" >&2
done
else
report_snapshot "INFO" "Snapshot update completed - no changes needed"
fi
else
report_snapshot "ERROR" "Failed to update snapshots"
echo " 📝 Update error details:" >&2
tail -5 "$UPDATE_OUTPUT_FILE" | while read line; do
echo " $line" >&2
done
fi
rm -f "$UPDATE_OUTPUT_FILE"
else
echo " ℹ️ Snapshot updates not needed at this time" >&2
fi
# 6. Clean up orphaned snapshots
echo "🧹 Checking for orphaned snapshots..." >&2
if [ "$SNAPSHOT_FILES_FOUND" -gt 0 ]; then
# This is a simplified check - in practice, you'd want more sophisticated orphan detection
POTENTIALLY_ORPHANED=0
for snapshot_file in "${SNAPSHOT_FILES[@]}"; do
SNAPSHOT_BASE=$(basename "$snapshot_file" .snap)
# Check if there's a corresponding test or component file
if ! find . -name "*${SNAPSHOT_BASE%.*}*" -type f \( -name "*.test.*" -o -name "*.spec.*" \) 2>/dev/null | head -1 | grep -q .; then
POTENTIALLY_ORPHANED=$((POTENTIALLY_ORPHANED + 1))
fi
done
if [ "$POTENTIALLY_ORPHANED" -gt 0 ]; then
report_snapshot "WARNING" "$POTENTIALLY_ORPHANED potentially orphaned snapshot files detected"
echo " 💡 Run 'npm test -- --updateSnapshot' to clean up unused snapshots" >&2
else
echo " ✅ No orphaned snapshots detected" >&2
fi
fi
# 7. Generate summary report
echo "" >&2
echo "📋 Jest Snapshot Management Summary:" >&2
echo "===================================" >&2
echo " 📄 Component: $COMPONENT_NAME" >&2
echo " 🧪 Test files found: $TEST_FILES_COUNT" >&2
echo " 📸 Snapshot files: $SNAPSHOT_FILES_FOUND" >&2
echo " ✅ Tests passed: $TESTS_PASSED" >&2
echo " ❌ Tests failed: $TESTS_FAILED" >&2
echo " 📸 Snapshots updated: $SNAPSHOTS_UPDATED" >&2
if [ "$SNAPSHOTS_UPDATED" -gt 0 ]; then
echo " 🎉 Status: SNAPSHOTS UPDATED - Review changes before committing" >&2
elif [ "$TESTS_FAILED" -gt 0 ]; then
echo " ⚠️ Status: TESTS FAILING - Fix issues before proceeding" >&2
elif [ "$TEST_FILES_COUNT" -eq 0 ]; then
echo " 📝 Status: NO TESTS - Consider adding snapshot tests" >&2
else
echo " ✅ Status: ALL GOOD - Snapshots are up to date" >&2
fi
echo "" >&2
echo "💡 Jest Snapshot Best Practices:" >&2
echo " • Review snapshot changes carefully before committing" >&2
echo " • Keep snapshots small and focused" >&2
echo " • Update snapshots only when UI changes are intentional" >&2
echo " • Use descriptive test names for better snapshot organization" >&2
echo " • Consider using 'toMatchInlineSnapshot' for small snapshots" >&2
echo " • Run 'npm test -- --updateSnapshot' to update all snapshots" >&2
# Exit with error if tests are failing for non-snapshot reasons
if [ "$TESTS_FAILED" -gt 0 ] && [ "$SNAPSHOTS_UPDATED" -eq 0 ]; then
echo "⚠️ Jest tests are failing - please review and fix issues" >&2
exit 1
fi
else
# Not a component file, exit silently
exit 0
fi
exit 0
Complete hook script that automatically updates Jest snapshots for modified components
#!/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" == *.jsx ]] || [[ "$FILE_PATH" == *.tsx ]]; then
echo "📸 Jest Snapshot Management for: $(basename "$FILE_PATH")" >&2
COMPONENT_NAME="${FILE_PATH%.*}"
TEST_COMMAND="npm test"
if [ -f "yarn.lock" ]; then
TEST_COMMAND="yarn test"
elif [ -f "pnpm-lock.yaml" ]; then
TEST_COMMAND="pnpm test"
fi
if $TEST_COMMAND -- --testPathPattern="$COMPONENT_NAME" --updateSnapshot --watchAll=false > /dev/null 2>&1; then
echo "✅ Snapshots updated successfully" >&2
else
echo "❌ Snapshot update failed" >&2
exit 1
fi
fi
exit 0
Complete hook configuration for .claude/settings.json to enable Jest snapshot auto-updating
{
"hooks": {
"postToolUse": {
"script": "./.claude/hooks/jest-snapshot-auto-updater.sh",
"matchers": ["write", "edit"]
}
}
}
Enhanced hook script for analyzing component changes using git diff with configurable threshold
#!/usr/bin/env bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
if command -v git &> /dev/null && git rev-parse --git-dir > /dev/null 2>&1; then
if git status --porcelain "$FILE_PATH" | grep -q '^.M'; then
LINES_CHANGED=$(git diff "$FILE_PATH" 2>/dev/null | grep -c '^[+-]' || echo "0")
if [ "$LINES_CHANGED" -gt 50 ]; then
echo "📈 Significant changes detected ($LINES_CHANGED lines modified)" >&2
SHOULD_UPDATE_SNAPSHOTS=true
else
echo "📝 Minor changes detected ($LINES_CHANGED lines modified)" >&2
SHOULD_UPDATE_SNAPSHOTS=false
fi
fi
fi
exit 0
Enhanced hook script for running tests and updating snapshots with parallel execution optimization
#!/usr/bin/env bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
COMPONENT_NAME="${FILE_PATH%.*}"
TEST_COMMAND="npm test"
if [ -f "yarn.lock" ]; then
TEST_COMMAND="yarn test"
elif [ -f "pnpm-lock.yaml" ]; then
TEST_COMMAND="pnpm test"
fi
TEST_OUTPUT_FILE="/tmp/jest_output_$$"
if $TEST_COMMAND -- --testPathPattern="$COMPONENT_NAME" --maxWorkers=2 --watchAll=false > "$TEST_OUTPUT_FILE" 2>&1; then
if grep -q 'snapshot.*differ' "$TEST_OUTPUT_FILE" 2>/dev/null; then
echo "📸 Snapshot mismatches detected - updating snapshots" >&2
$TEST_COMMAND -- --testPathPattern="$COMPONENT_NAME" --updateSnapshot --maxWorkers=2 --watchAll=false
fi
else
echo "❌ Tests failed - checking for snapshot issues" >&2
fi
rm -f "$TEST_OUTPUT_FILE"
exit 0
Enhanced hook script for detecting orphaned snapshot files with test file association validation
#!/usr/bin/env bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
FILE_DIR="$(dirname "$FILE_PATH")"
SNAPSHOT_DIRS=("__snapshots__" "snapshots" "__tests__/__snapshots__" "tests/__snapshots__")
SNAPSHOT_FILES=()
for dir in "${SNAPSHOT_DIRS[@]}"; do
if [ -d "$FILE_DIR/$dir" ]; then
while IFS= read -r -d '' file; do
SNAPSHOT_FILES+=("$file")
done < <(find "$FILE_DIR/$dir" -name "*.snap" -print0 2>/dev/null)
fi
done
if [ ${#SNAPSHOT_FILES[@]} -gt 0 ]; then
echo "📁 Found ${#SNAPSHOT_FILES[@]} snapshot files" >&2
for snapshot in "${SNAPSHOT_FILES[@]}"; do
SNAPSHOT_BASE=$(basename "$snapshot" .snap)
if ! find . -name "*${SNAPSHOT_BASE%.*}*" -type f \( -name "*.test.*" -o -name "*.spec.*" \) 2>/dev/null | head -1 | grep -q .; then
echo "⚠️ Orphaned snapshot detected: $(basename "$snapshot")" >&2
fi
done
fi
exit 0
Detection too broad (matches all .js/.ts). Add matchers: 'matchers': ['write:/*.{test,spec}.{js,ts,jsx,tsx}', 'edit:/*.{test,spec}.{js,ts,jsx,tsx}'] to trigger only on test files. Verify file path patterns match test files. Test with various file types.
testNamePattern with component name unreliable. Use --testPathPattern: '$TEST_COMMAND -- --testPathPattern="$COMPONENT_NAME" --watchAll=false'. Targets files not test descriptions. Verify component name extraction. Test with various component names.
No worker limit causes resource exhaustion. Add '--maxWorkers=2': '$TEST_COMMAND -- --testPathPattern="$TEST_PATTERN" --maxWorkers=2 --watchAll=false' for stable CI execution. Verify worker count. Test with various test suite sizes.
Old snapshots persist when components renamed. Run cleanup: 'npm test -- --updateSnapshot --clearCache' deleting unused snapshots. Or manually remove from snapshots directory. Verify snapshot cleanup. Test with component renaming.
Conservative threshold causes excessive updates. Increase: 'if [ "$LINES_CHANGED" -gt 50 ]; then' for major changes only. Or check specific files: test if modified file is component. Verify threshold configuration. Test with various change sizes.
Jest cache may be stale. Clear cache: 'npm test -- --clearCache'. Verify Jest configuration. Check module resolution paths. Ensure all dependencies installed. Verify test environment setup.
Hook may not detect snapshot mismatches. Check test output for snapshot-related messages. Verify --updateSnapshot flag is passed. Check Jest configuration for snapshot settings. Verify snapshot file permissions. Test with explicit snapshot updates.
Pattern matching may be too strict. Adjust snapshot base name extraction. Verify test file naming conventions. Check for test files in different directories. Verify snapshot file associations. Test with various project structures.
Show that Jest Snapshot Auto Updater - Hooks is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.
[](https://heyclau.de/entry/hooks/jest-snapshot-auto-updater)Jest Snapshot Auto Updater - Hooks side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.
| Field | Automatically updates Jest snapshots when component files are modified significantly. Open dossier | Automatically creates or updates test files when React 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 | Automatically formats code files after Claude writes or edits them using industry-standard formatters including Prettier 3.6.2+ (JavaScript/TypeScript/Web), Black or Ruff (Python), gofmt (Go), and rustfmt (Rust). Open dossier |
|---|---|---|---|---|
| Next steps | ||||
| Trust | ||||
| Review status | ReviewedMaintainer reviewed | ReviewedMaintainer reviewed | ReviewedMaintainer reviewed | ReviewedMaintainer reviewed |
| Package trust | Package not verified | Package not verified | Package not verified | Package not verified |
| Source provenance | Source-backed | Source-backed | Source-backed | Source-backed |
| Submitter | — | — | — | — |
| Install risk | Review first | Review first | Review first | Review first |
| Notes | Safety ✓ Privacy ✓ | Safety ✓ Privacy ✓ | Safety ✓ Privacy ✓ | Safety ✓ Privacy ✓ |
| Brand | — | — | — | — |
| Category | hooks | hooks | hooks | hooks |
| Source | source-backed | source-backed | source-backed | source-backed |
| Author | JSONbored | JSONbored | JSONbored | JSONbored |
| Added | 2025-09-19 | 2025-09-19 | 2025-09-19 | 2025-09-19 |
| Platforms | Claude Code | Claude Code | Claude Code | Claude Code |
| Source repo | — | — | — | — |
| 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. | ✓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. | ✓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. | ✓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. | ✓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 | | | | |
| Config | | | | |
| Citations | ||||
| Claim | Unclaimed | Unclaimed | Unclaimed | Unclaimed |
Source-backed guides for putting this to work.
Set autoMode.hard_deny rules to block risky actions in auto mode.
Loading live community signals…
A short, calm digest of reviewed Claude resources. Unsubscribe any time.