A test that waits through the whole cooldown to reach half-open is testing the CI machine's clock, not the circuit breaker's recovery. A test that only counts failures can also miss the dangerous bug: two calls enter as probes while the dependency is still recovering.
The simple approach is to inject the clock used by the breaker. The suite advances time with a local function, drives the circuit through closed, open, and half-open, and counts how many calls reached the dependency. The guide to using a circuit breaker for AI agent tools explains the production behavior; this article focuses on proving the state machine.
Short answer
- Inject
now()or use the test runner's fake clock. Do not usesleepto cross the cooldown.- Check the threshold boundary: the call that reaches the threshold still fails, but the next one never reaches the dependency.
- After the cooldown, admit one half-open probe and reject a second call while the first is pending.
- Test both probe outcomes: success closes the circuit; failure opens it again.
What does the test need to prove?
A circuit breaker sits between a caller and a dependency. In closed, calls pass through and classified failures accumulate. In open, the breaker fails fast without calling the dependency. After an interval, it allows one controlled call in half-open to find out whether the dependency has recovered.
AWS Prescriptive Guidance on the circuit-breaker pattern describes this behavior: after the threshold is reached, the circuit stops routing calls and returns an immediate failure; it then checks recovery and resumes routing when the call succeeds. That sequence becomes a small test matrix:
| Scenario | Expected state | Observation that prevents a false green |
|---|---|---|
| Failures below the threshold | closed |
The dependency receives the calls. |
| Failure that reaches the threshold | open |
The failed call counts; the next call is blocked. |
| Call during the cooldown | open |
The fake executor is not called. |
| First call after the cooldown | half-open |
One probe is admitted. |
| Successful probe | closed |
The failure counter is cleared. |
| Failed probe | open |
A new cooldown begins. |
Do not mix failure-policy testing with time testing. An invalid argument should not open the circuit just because an exception was thrown. In this post, the fixture treats every dependency error as a failure to keep the example short. In a real application, extract classification into its own function and test that function separately.
If you are deciding where this fixture ends and an integration test begins, compare unit and integration testing in Node.js. The in-memory breaker proves the local decision; the real dependency needs a different boundary.
Make the cooldown controllable
The breaker does not need to schedule a timer to represent the cooldown. It can store the instant when it opened and check a clock when the next call arrives. That makes the state observable and lets the test advance time without waiting.
This is a small breaker for the fixture. It allows one half-open probe at a time and restarts the cooldown when that probe fails.
export class CircuitOpenError extends Error {
constructor(retryAfterMs) {
super("tool dependency is temporarily unavailable");
this.name = "CircuitOpenError";
this.retryAfterMs = retryAfterMs;
}
}
export class CircuitBreaker {
constructor({ failureThreshold, cooldownMs, now = () => Date.now() }) {
this.failureThreshold = failureThreshold;
this.cooldownMs = cooldownMs;
this.now = now;
this.state = "closed";
this.failures = 0;
this.openedAt = null;
this.probeInFlight = false;
}
getState() {
if (
this.state === "open" &&
this.openedAt !== null &&
this.now() - this.openedAt >= this.cooldownMs
) {
this.state = "half-open";
}
return this.state;
}
async run(operation) {
const state = this.getState();
if (state === "open") {
const elapsed = this.now() - this.openedAt;
throw new CircuitOpenError(Math.max(0, this.cooldownMs - elapsed));
}
const isProbe = state === "half-open";
if (isProbe && this.probeInFlight) {
throw new CircuitOpenError(0);
}
if (isProbe) this.probeInFlight = true;
try {
const value = await operation();
this.state = "closed";
this.failures = 0;
this.openedAt = null;
return value;
} catch (error) {
this.failures += 1;
if (isProbe || this.failures >= this.failureThreshold) {
this.state = "open";
this.openedAt = this.now();
this.failures = 0;
}
throw error;
} finally {
if (isProbe) this.probeInFlight = false;
}
}
}
A production implementation needs more decisions: which errors count, whether state is shared across processes, how to expire a probe that never settles, and which structured result the tool returns to the agent. The fixture does not solve those decisions. It creates a small boundary so the tests do not depend on a real API.
Test opening without waiting
The first case should show the exact boundary. Configure two failures, open the circuit, and try a third call. The third operation must not increment the fake executor's counter because the breaker has to block it before the dependency.
import assert from "node:assert/strict";
import { test } from "node:test";
import { CircuitBreaker, CircuitOpenError } from "./circuit-breaker.mjs";
function makeClock() {
let current = 0;
return {
now: () => current,
advance: (milliseconds) => {
current += milliseconds;
},
};
}
test("opens after the threshold and blocks the next call", async () => {
const clock = makeClock();
const breaker = new CircuitBreaker({
failureThreshold: 2,
cooldownMs: 1_000,
now: clock.now,
});
let dependencyCalls = 0;
const unavailable = async () => {
dependencyCalls += 1;
throw new Error("dependency down");
};
await assert.rejects(() => breaker.run(unavailable));
await assert.rejects(() => breaker.run(unavailable));
assert.equal(breaker.getState(), "open");
await assert.rejects(
() => breaker.run(async () => "unexpected"),
CircuitOpenError,
);
assert.equal(dependencyCalls, 2);
});
CircuitOpenError matters to the caller. An agent or client can turn it into an unavailable response, use a fallback, or request review. The test should check both the state and the absence of the external call. Checking only the final message lets a mock hide a call that should never have happened.
Test the single half-open probe
The recovery case starts by advancing the clock exactly to the end of the cooldown. Then leave the first probe pending. While it is unfinished, the second call must be blocked. Finally, release the probe and confirm that the circuit closed.
test("admits one half-open probe and closes after recovery", async () => {
const clock = makeClock();
const breaker = new CircuitBreaker({
failureThreshold: 1,
cooldownMs: 1_000,
now: clock.now,
});
let dependencyCalls = 0;
await assert.rejects(() =>
breaker.run(async () => {
dependencyCalls += 1;
throw new Error("dependency down");
}),
);
clock.advance(1_000);
let releaseProbe;
const probeResult = new Promise((resolve) => {
releaseProbe = resolve;
});
const firstProbe = breaker.run(async () => {
dependencyCalls += 1;
await probeResult;
return "recovered";
});
await assert.rejects(
() => breaker.run(async () => "second probe"),
CircuitOpenError,
);
releaseProbe();
assert.equal(await firstProbe, "recovered");
assert.equal(breaker.getState(), "closed");
assert.equal(dependencyCalls, 2);
});
This case catches a failure that the threshold test cannot see. The first half-open call may consume the only permit, while an incorrect implementation still releases concurrent calls. A public report of a breaker stuck in HALF_OPEN describes another variation: the probe never resolves or rejects, and its slot is never recovered. Use this kind of scenario to make a probe lease or timeout an explicit design decision.
Test recovery that fails too
A suite that tests only a successful probe can close the circuit too early. After the cooldown, make the probe fail and check three things:
- the state returned to
open; - an immediate call is still blocked;
- the new cooldown starts at the probe failure, not at the original opening.
That last detail catches a bug where the circuit enters half-open, fails, and allows calls again immediately. Time should be an observable dependency, not a hidden test detail.
When should you use Node's mock.timers?
If the code schedules setTimeout or reads Date.now() directly, Node's built-in runner provides timer mocking and methods such as tick() to advance time. The Node.js node:test documentation shows how to enable mocked Date and timers and advance time without waiting for the real duration.
Even so, do not use timer mocking to hide a difficult contract. When the rule is simply "has the cooldown ended?", injecting now() usually makes the fixture simpler. Use mock.timers when scheduling itself is the behavior under test, such as a timer that expires a probe or triggers a transition without a new call.
With either approach, reset the clock state between tests. A pending timer or shared fake date can contaminate the next case and produce a suite that passes alone but fails as a group.
What still needs an integration test?
The in-memory breaker proves the local state machine. It does not prove that two Cloud Run instances, workers, or pods share the same decision. It also does not prove distributed locking, persisted cooldowns, cancellation of a pending probe, or correct classification of provider errors.
In an agent context, RemoteCode is the author's tool for working with engineering loops. This mention describes the tool's use, not a production validation or a performance claim.
For the integration layer, use a controlled dependency and check the network contract: timeouts, 5xx responses, rate limits, transition logs, and the result returned to the tool. If the agent can repeat a call after receiving open, test the runner's behavior too. The guide to testing an agent without extra LLM calls helps keep that loop deterministic.
The useful split is this: the unit test proves that the state machine blocks, probes, closes, and reopens; the integration test proves that the adapter classifies failures and that the observed state corresponds to the dependency you actually protect. Neither one turns a cooldown parameter into a universal availability guarantee.