Claude CodeBeginner

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.

7 minBeginner

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.

zsh - my-app
$npx vitest run src/cart/total.test.ts
FAIL src/cart/total.test.ts > applies coupon once
Expected: 90
Received: 81
at cartTotal (src/cart/total.ts:24:18)
$

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.

Claude Code
You
This test fails: expected 90, received 81. Explain the root cause in cartTotal before changing anything. Do not modify the test.
Agent
The coupon is applied twice: once in cartTotal and again in applyCoupon, so 100 becomes 90 then 81. The fix is to remove the duplicate multiplication in cartTotal, not to touch the test.
Ask for an explanation before any fix.

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.

src/cart/total.ts
-  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.

zsh - my-app
$npx vitest run src/cart/total.test.ts
Tests 1 passed (1)
$
Watch what gets edited
If a fix changes the test instead of the code, the bug is still there and the test now lies. Always confirm the diff lands in the source file.

Result: a double-discount bug found and removed in the source, with the original test left untouched and now passing.

Watch related tutorials

Tags
#debugging#testing#root-cause