Debug a failing Node test with an AI coding agent
In JavaScript, a wrong type inside an arithmetic loop rarely throws where the bug happens. Adding a number and a string coerces the number into a string and the test fails later at an assertion. Mercury CLI ships a built-in Debug tool speaking the Debug Adapter Protocol (DAP) and a Test tool whose debug operation launches a failing node:test, vitest or jest test directly under the bundled js-debug adapter.
This walkthrough uses a small order ledger in Node where one daily-report test fails out of twelve tests. The example is a public repository anyone can clone: ledger-debug-demo.
The failing test and example code
The ledger reads 2,000 orders from data/orders.ndjson, computes each order's discounted subtotal and shipping cost, and totals revenue for a given day. Under node/:
node/src/parse.js:
import { readFileSync } from 'node:fs'
export function parseOverride(value) {
if (value === null || value === undefined || value === '') return null
if (Number.isInteger(value)) return value
if (typeof value === 'string') {
const trimmed = value.trim()
if (/^\d+$/.test(trimmed)) return Number(trimmed)
return trimmed.replace(/^["']|["']$/g, '')
}
return null
}
node/src/shipping.js:
export function shippingCost(order) {
const override = order.shippingOverride
if (override === 'waived') return 0
if (override !== null && override !== undefined) return override
return tableRate(order.region, order.weightGrams)
}
node/src/total.js:
import { discountedSubtotal } from './pricing.js'
import { shippingCost } from './shipping.js'
export function orderTotal(order) {
const subtotal = discountedSubtotal(order)
const shipping = shippingCost(order)
return subtotal + shipping
}
node/src/report.js:
import { orderTotal } from './total.js'
export function dailyReport(orders, date) {
const dayOrders = orders.filter((order) => order.date === date)
let revenuePence = 0
for (const order of dayOrders) {
revenuePence += orderTotal(order)
}
return {
date,
orderCount: dayOrders.length,
revenuePence,
}
}
The failing test in node/test/ledger.test.js asks for the report of one day, 19 October, and expects 67 orders and a revenue of 656094 pence.
Running node --test inside node/ (or node --test node/test/ledger.test.js from the repository root) shows 11 passing tests and 1 failure (the test's name line is left out here):
node --test
failing tests:
test at test/ledger.test.js:124:1
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
+ actual - expected
+ '197153750499679513505240074952409010395503523459000500043454245120451005012535134231054510145710013980674014795235351798571953495660086003890301045751035052685245750565951111599001960511295240014790150687795935999523552144518548220556145112951705271652795132755250118501149549951374512583959513080'
- 656094
at TestContext.<anonymous> (test/ledger.test.js:127:10)
What guessing from the traceback gets wrong
Because JavaScript + concatenates instead of throwing when one side is a string, no error fires inside node/src/total.js or node/src/report.js. The stack trace names only test/ledger.test.js:127 and prints a long concatenated string where 656094 was expected.
The stack trace never mentions src/total.js, src/shipping.js or src/parse.js, and gives no clue which of that day's 67 orders spoiled the sum. All 11 other tests, including the unit tests for parseOverride and shippingCost, pass. Guessing from the assertion output often leads to wrapping Number(...) around orderTotal(order) in src/report.js, which masks the bad value instead of finding where a string entered the ledger.
Debug the failing test in Mercury
Clone the repository (git clone https://github.com/Whq02/ledger-debug-demo), open its node/ folder in your terminal, start mercury, and ask it to debug the failure:
One test fails. Find out why with the debugger and fix the cause.
The model picks its own steps, so the order in your run can differ. These are the calls that find the cause.
1. Launch the failing test under js-debug
The agent runs Test run to read the summary and failing test name, then calls Test debug for that test. For the Node runners, a test is spelled file::name or as a bare name from the latest run. Mercury asks permission for the launch, starts node:test under the bundled js-debug adapter with no launch configuration written and no runner arguments reconstructed by hand, and pauses before the test body runs, ready for breakpoints.
When js-debug starts child sessions (one session per Node process, and a test runner may start one per file), each child joins the same debug tree (bounded at 16 children and 4 levels deep by default). Every Debug operation addresses root and child sessions uniformly.
2. Set a conditional breakpoint and continue
Instead of stepping through every order, the agent calls Debug breakpoints on src/total.js line 7 with a condition:
{
"file": "src/total.js",
"breakpoints": [
{
"line": 7,
"condition": "typeof shipping !== 'number'"
}
]
}
Then the agent calls Debug continue. Execution runs through the valid orders and stops once at src/total.js:7 on the offending order.
3. Read the live values
On the stopped frame, the agent calls Debug scopes and variables (or evaluate, which defaults frameId to the top frame of the thread that stopped last). The live locals read:
subtotal = 3750
shipping = '499'
order.id = 'ORD-11203'
order.shippingOverride = '499'
4. Apply the one-line fix
Reading '499' as a string points straight to parseOverride in src/parse.js:7. The input record for ORD-11203 has "shippingOverride": "\"499\"". Because const trimmed = value.trim() tested /^\d+$/ before stripping outer quotes, '"499"' skipped Number(trimmed), stripped its quotes on line 9, and returned '499' as a string.
The agent calls Debug disconnect to end the debug session, then makes the one-line fix at src/parse.js:7:
const trimmed = value.trim().replace(/^["']|["']$/g, '')
5. Rerun the test and the suite
The agent calls Test rerunFailed to check the recorded failure, then Test run to verify the full suite. All 12 tests pass (tests 12, pass 12, fail 0).
Using vitest and jest
Test debug also supports vitest and jest under the bundled js-debug adapter, with no launch configuration written and no runner arguments reconstructed by hand, pausing before the test body runs, ready for breakpoints:
vitestruns in one worker with its timeout off.jestruns in-band.- Spell the test as its runner names it:
file::nameor a bare name from the latest run. Testrunreadsvitest's andjest's JSON reports and returns passed, failed and skipped counts with each failing case's name, file, line and message, asnode-testdoes from its summary.TestrerunFailedselects those recorded failures by the names the reporter recorded.- When a
runorrerunFailedselection matches nothing innode-test,vitestorjest,Testreportsno test matched <selection>: <the runner's own words>with zero counts and ano-matchverdict.
Adapter settings and health check
js-debugfor Node and TypeScript is vendored in the Mercury build. SetMERCURY_JS_DEBUG_DAPto pin a custom copy.launch,attach,continue,next,stepIn,stepOut,pauseandrestartaccepttimeoutMs(default10,000milliseconds; longer waits are allowed). Reaching the deadline reports that the program is still running without terminating it; usestatusto inspect it ordisconnectto end the session.- Run
mercury healthor enter/healthin a session and read theTools withheldrow to confirmDebugis available. SettingMERCURY_DAP=0removesDebugfrom the tool catalogue.