“Done!” with failing tests is annoying. A Stop hook runs when Claude wants to finish its turn and can send it back to work.
The script, saved as .claude/hooks/tests-pass.sh and made executable:
#!/bin/bash
INPUT=$(cat)
if [ "$(echo "$INPUT" | jq -r '.stop_hook_active')" = "true" ]; then
exit 0
fi
if ! npm test --silent >/dev/null 2>&1; then
echo '{"decision": "block", "reason": "The tests fail. Run npm test and fix them before you stop."}'
fi
And in .claude/settings.json:
{ "hooks": { "Stop": [ { "hooks": [ { "type": "command", "command": ".claude/hooks/tests-pass.sh" } ] } ] } }
When the tests fail, the hook prints decision: block with a reason. Claude doesn’t stop, it gets the reason as feedback and keeps working.
The stop_hook_active check matters. It is true when Claude is already continuing because of a Stop hook, and exiting there lets Claude stop after one extra round instead of looping. Claude Code also overrides a Stop hook that blocks eight times in a row without a tool call in between.
A Stop hook runs at the end of every turn, also when you only asked a question. A slow test suite then makes every answer slow, so a fast subset of the tests is the better choice here, in my view.
Further reading: Automate actions with hooks, Hooks reference