Your test suite passes. It always passes, because every third-party API in it is a stub that answers 200 OK in a millisecond. Then the payment provider has a bad afternoon, starts answering 503 to one request in five, and you find out in production that your client retries instantly, forty times, and then shows the customer a blank page.
None of that was hard to catch. It just never ran in a test. This guide shows how to make API failure testing part of every pull request: the tests you already have, pointed at dependencies that fail on purpose, with a pass or fail grade on how your code coped.
Chaos engineering, minus the chaos team
Chaos engineering usually gets pitched as killing servers in production while a dedicated team watches dashboards. That's valuable at scale, and most teams will never do it.
The cheap version catches most of the same client-side bugs. Your code doesn't care whether the 503 came from a real outage or a fake one. What matters is what it does next:
- Does it retry a transient failure, or give up on the first one?
- Does it wait between retries, and does the wait grow?
- Does it honor
Retry-Afteron a429? - Does it stop retrying a
422, which will never succeed? - Does it time out on a hung connection, or wait forever?
- Does a retried
POSTkeep the sameIdempotency-Key, so the customer isn't charged twice?
Every one of those is a property of your client code, and every one is testable in CI. You need two things: a dependency that misbehaves on demand, and something that watches the traffic and grades it.
What to break first: two scenarios that cover most outages
Start small. Most real incidents with third-party APIs look like one of these:
| Scenario | What the API does | What it catches |
|---|---|---|
| Flaky gateway | 503 on 20% of requests, plus 500 to 3000 ms of extra latency on some |
Missing retries, retries with no backoff, timeouts set too tight |
| Rate limited | 429 with Retry-After: 2, twice, then success |
Ignoring Retry-After, retry storms, giving up too early |
A third worth adding later is a hanging dependency: the API accepts the connection and never answers. That catches the client with no timeout at all, which is the most expensive bug on this list because it ties up a worker until something upstream kills it.
In Jitterbox, a fake API and its failure scenarios fit in one file, jitterbox.yaml, that lives in your repo:
project: checkout-ci
endpoints:
- method: POST
path: /payments
status: 201
json: { id: pay_123, status: succeeded }
- method: GET
path: /payments/{id}
template: true
json: { id: "{{path.id}}", status: succeeded }
scenarios:
- name: Flaky gateway
enabled: false
endpoints: ["POST /payments"]
faults:
- error: 503
rate: 20%
- latency: 500-3000ms
rate: 20%
- name: Rate limited
enabled: false
faults:
- error: 429
headers: { Retry-After: "2" }
pattern: xx.
pattern: xx. reads as "fail, fail, pass", repeating. enabled: false keeps both scenarios off, so the fake API behaves normally until a CI run switches one on. Create the project with npx jitterbox apply (after npx jitterbox login), and check the plan first with npx jitterbox diff.
During the beta a workspace gets one project, ten endpoints and two scenarios, which is exactly enough for this setup. For the hanging case, see the per-request header in the determinism section below.
Point your tests at the fake API, not the real one
Your app almost certainly reads the API's base URL from config already. If it doesn't, that's the first change, and it's a good one regardless:
// payments.ts
const BASE_URL = process.env.PAYMENTS_API_URL ?? "https://api.payments.example";
export async function createPayment(amountCents: number, idempotencyKey: string) {
const res = await fetch(`${BASE_URL}/payments`, {
method: "POST",
headers: { "Content-Type": "application/json", "Idempotency-Key": idempotencyKey },
body: JSON.stringify({ amount: amountCents }),
signal: AbortSignal.timeout(5_000),
});
if (!res.ok) throw new Error(`payments: ${res.status}`);
return res.json();
}
jitterbox run sets JITTERBOX_BASE_URL (the project's mock URL, like https://<projectKey>.jitterbox.dev) for the command it runs. The command goes through a shell, so you can map it onto your own variable in the same line:
npx jitterbox run --scenario "Flaky gateway" -- 'PAYMENTS_API_URL=$JITTERBOX_BASE_URL npm test'
Only your test environment should ever see that URL. More on that at the end.
Keep failure tests deterministic
A test that fails one run in five because a dice roll landed differently is worse than no test. Four tools keep failure tests repeatable:
- Sequences instead of percentages for anything a test asserts on.
pattern: xx.fails exactly the first two requests and lets the third through.jitterbox runresets every scenario's counter before it starts, so each run begins at step one. - Run those tests serially. The sequence counter belongs to the scenario, not to a test, so parallel workers would share it and interleave.
jest --runInBand,vitest --no-file-parallelismorpytest -p no:xdistkeep the order fixed. X-Jitterbox-Seedfixes the random draw behindrate: 20%for a request, so a failure you saw once can be replayed exactly. Send the same seed, get the same decision.X-Jitterbox-Faultforces one fault on one request and skips scenarios entirely. It's the right tool for a focused test:X-Jitterbox-Fault: http_error=503,latency=1500,malformed=invalid_json, ortimeout=8000for the hanging dependency (8 seconds, then a504).noneforces a clean response.
One more header helps the grade rather than the test. X-Jitterbox-Operation tells Jitterbox which requests are one logical call and its retries. Without it, Jitterbox groups attempts by fingerprint (same method, path, body and User-Agent within 60 seconds of a failure), which is usually right. In a test suite that fires many similar calls, set it to the test's name and the grouping is exact.
Run it in GitHub Actions
The Jitterbox Action wraps jitterbox run: it switches the scenario on, runs your command, switches it back off (even if the tests crash), grades the traffic and fails the job if the client misbehaved.
name: resilience
on: pull_request
jobs:
api-failures:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
- run: npm ci
- uses: MadhavKauntia/jitterbox-cli@v1
with:
token: ${{ secrets.JITTERBOX_TOKEN }}
scenario: Rate limited
command: PAYMENTS_API_URL=$JITTERBOX_BASE_URL npm test -- --runInBand
require: respects-retry-after,backs-off
junit: jitterbox-junit.xml
The token is a project API key from Settings → API keys, stored as a repository secret. It's shown once, only a hash is kept, and it's deliberately narrow: it can switch and reset scenarios, read requests and reports, and take the run lock, but it can't change your mocks, see other projects or create keys. If it leaks from a fork's logs, the damage is someone toggling a fake API.
The Action writes the report card to the job summary and adds an annotation explaining any failure. Outside GitHub, the same thing is one command in any CI, with the key in a JITTERBOX_TOKEN secret variable:
npx jitterbox run --scenario "Rate limited" --junit report.xml -- 'PAYMENTS_API_URL=$JITTERBOX_BASE_URL npm test'
What fails the build
After the tests finish, Jitterbox grades every operation it saw against seven checks: retries transient failures, respects Retry-After, backs off, gives up eventually, doesn't retry permanent errors, keeps the idempotency key, and times out instead of hanging.
- A check marked FAIL fails the run. Retrying within 200 ms of a failure, ignoring
Retry-Afteror retrying a422all count. - Warnings, such as a
POSTretried with noIdempotency-Keyat all, pass unless you setfail-on: warn. requirenames checks that must actually pass. If the scenario never triggered and a required check went untested, the run fails. Without it, a green build could just mean nothing broke.
The exit code tells your pipeline why:
| Exit code | Meaning |
|---|---|
0 |
Tests passed and the client coped |
| your command's code | Your tests failed on their own |
3 |
Tests passed, but the resilience report failed |
4 |
No requests reached Jitterbox |
5 |
Timed out waiting for another run on the same project |
6 |
Bad or missing token |
Exit 4 is nearly always a wiring bug: the tests still call the real API, or a cached client was built before the environment variable was set. Fix that before trusting a green run.
Exit 5 comes from the run lock. Scenarios apply to the whole project, so jitterbox run takes a lease before touching anything and a second run waits (up to 600 seconds by default) instead of interfering. Give each pipeline its own project and nothing ever waits.
Keep the fake API in version control
jitterbox.yaml holds no secrets, so commit it next to the tests that depend on it. Reviewers then see "the rate-limit scenario now returns Retry-After: 30" in the same diff as the code that handles it.
To catch drift between the file and the project, run jitterbox diff --exit-code in CI. It exits 1 when the project no longer matches the file:
- run: npx jitterbox diff --exit-code
env:
JITTERBOX_TOKEN: ${{ secrets.JITTERBOX_PERSONAL_TOKEN }}
Note the different secret. diff and apply read and change mocks, which a project API key can't do, so they need a personal token (jbp_…, from Settings → Account). Keep that one out of pull-request jobs from forks, and run npx jitterbox apply only on your main branch, after review.
Where this approach stops
A few honest limits:
- Never point production at a mock. The base URL switch belongs in test configuration only. If your app has a single env var for the API URL, make sure deploy config can't inherit the test value.
- It tests the client, not the provider. Jitterbox can't tell you how Stripe or OpenAI actually fail next Tuesday. It tells you whether your code survives the failure modes they document and the ones every HTTP API eventually has. For LLM providers specifically, the LLM failure testing docs list what the real OpenAI and Anthropic SDKs do with each fault.
- It isn't a load test. The beta allows 500 mock requests a day and 10 per second per project. Plenty for a test suite, not for a soak test.
- Timeouts make slow tests. A hanging-dependency test takes as long as your client's timeout. Keep those to a handful, run them in a separate job if they hurt PR times.
Pick one client that calls one critical API, payments or auth or your LLM provider, and wire up the Rate limited scenario first. It's the one most clients get wrong, and the report will tell you within one run whether yours does. The CI docs have every option, and How it works covers the rest of what Jitterbox can break.