How to Debug a Failing Test with Claude Code
Feed Claude Code the failing test output and let it trace the root cause instead of guessing at fixes.
A red test tells you something broke but not why. Claude Code is good at turning a stack trace into a root cause when you give it the full failure output and let it read the surrounding code. The mistake to avoid is asking it to just make the test pass, which invites it to weaken the assertion instead of fixing the bug.
What you need
- Claude Code running in the project
- A test that is currently failing
- The full failure output, including the stack trace
Step 1: Capture the full failure
Run the failing test and copy everything, the expected value, the received value, and the stack trace. The received value and the line numbers are what point Claude at the real problem.
Step 2: Ask for the root cause, not just a green test
Paste the failure and ask Claude to explain why expected and received differ before proposing a fix. Requesting the explanation first keeps it honest and stops it from editing the test to match the bug.
Step 3: Apply the fix to the source
Once the explanation makes sense, let Claude fix the source file. Confirm the change touches the logic, not the assertion. If you see a diff editing total.test.ts instead of total.ts, stop and push back.
- const discounted = subtotal * couponRate;
- return applyCoupon(discounted, coupon);
+ return applyCoupon(subtotal, coupon);Step 4: Re-run to confirm
Run the test again. A pass here means the assertion was right all along and the source had the bug, which is the outcome you want.
Result: a double-discount bug found and removed in the source, with the original test left untouched and now passing.
Watch related tutorials
1:42:18
28:14
41:09
9:47
8:23
52:31