Testing Claude API Calls in a CI/CD Pipeline
Testing Claude API calls inside a CI/CD pipeline means verifying that your prompts, parsing logic, and error handling behave correctly on every commit — without burning through API credits, leaking keys in build logs, or letting slow network calls block your deploys. The short answer: use a layered strategy of unit tests with mocked responses, a small number of contract tests against real completions, and a post-deploy smoke test, each gated behind environment-specific credentials and timeouts.
Most teams get this wrong in one of two directions. Either they mock everything and ship a pipeline that's green but never actually calls the real API (so you discover breakage in production), or they call the live API on every test run and end up with flaky, slow, expensive pipelines that fail randomly when the model takes 8 seconds to respond. The fix is to split your test suite by what it's actually verifying.
The three layers of Claude API testing in CI
1. Unit tests — mock the API entirely
Unit tests should never make network calls. They exist to verify your request-building logic, response parsing, and error-handling branches.
// __mocks__/claudeClient.js
export const mockClaudeResponse = (content) => ({
id: "msg_test123",
content: [{ type: "text", text: content }],
stop_reason: "end_turn",
usage: { input_tokens: 42, output_tokens: 18 }
});
test("extracts summary field from response", () => {
const response = mockClaudeResponse("Summary: all tests passed");
const result = extractSummary(response);
expect(result).toBe("all tests passed");
});
Run these on every push, every PR, no secrets required. They should take milliseconds and never touch rate limits.
2. Contract tests — a small number of real calls
Contract tests confirm that your assumptions about the API's shape (fields, error codes, streaming events) still hold. You don't need hundreds of these — five to ten targeted calls covering your core use cases is enough. Run them on merge to main, not on every commit, to control cost and latency.
#!/bin/bash
# contract-test.sh
response=$(curl -s -w "\n%{http_code}" https://api.subtoapi.app/v1/messages \
-H "Authorization: Bearer $SUBTOAPI_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-sonnet-4-5",
"max_tokens": 50,
"messages": [{"role": "user", "content": "Reply with exactly: OK"}]
}')
body=$(echo "$response" | head -n -1)
status=$(echo "$response" | tail -n 1)
if [ "$status" -ne 200 ]; then
echo "Contract test failed: HTTP $status"
exit 1
fi
echo "$body" | jq -e '.content[0].text | test("OK")' > /dev/null || {
echo "Unexpected response shape"
exit 1
}
Using a single API endpoint across environments — like SubToAPI's /v1/messages — keeps these contract tests identical whether they run against staging or production, since the request format doesn't change between the Solo, Team, or Scale plans.
3. Post-deploy smoke tests
After a deploy, run one or two real requests against the live endpoint to confirm the deployment actually works end-to-end — auth, networking, and the model all responding. Keep these minimal; this is not where you test prompt quality.
Handling secrets and rate limits in CI
Three practical rules that prevent the most common pipeline failures:
- Never hardcode keys. Store
SUBTOAPI_KEY(or your provider's key) as an encrypted CI secret, scoped to the pipeline stage that needs it. Unit tests shouldn't have access to it at all — if they do, that's a sign they're not properly mocked. - Separate test and production keys. Issue a dedicated key for CI runs so you can track usage and revoke it independently without affecting production traffic. SubToAPI's dashboard lets you generate multiple
sub_live_...keys per team, which makes this easy to isolate. - Set explicit timeouts and retries. Model responses can occasionally take longer than usual. A CI job with no timeout will hang; one with no retry will fail on a single transient blip. 15–20 seconds with one retry is a reasonable default for short completions.
async function callWithRetry(payload, retries = 1) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 15000);
try {
const res = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify(payload),
signal: controller.signal
});
clearTimeout(timeout);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (err) {
if (retries > 0) return callWithRetry(payload, retries - 1);
throw err;
}
}
Reducing flakiness from non-deterministic output
Language model output isn't byte-identical between runs even at low temperature, so assertions need to target structure, not exact text:
- Assert on JSON schema or field presence rather than exact strings.
- Set
temperature: 0for contract tests to reduce (not eliminate) variance. - Use
"Reply with exactly: X"style prompts for deterministic checks when you just need to confirm connectivity. - For tool-use testing, assert that the expected tool name and argument keys appear — see /docs/tools for the request/response shape if you're testing function-calling behavior.
Keeping pipelines fast and affordable
Live API calls in CI cost money and add latency to every build. A few habits keep this under control:
- Cap contract tests to
max_tokensvalues just large enough to verify the response (20–100 tokens is usually enough). - Run full contract suites only on merges to main or nightly, not on every PR push.
- Use a staging-tier API key with a lower quota so a runaway loop in a bad PR can't rack up a large bill.
- If you're evaluating providers, check /pricing — a predictable flat per-seat cost (Solo €9, Team €19/seat, Scale €49/seat) makes CI usage easier to budget than raw token-metered billing, since your testing cost doesn't scale unpredictably with build frequency.
Getting started
If you're setting this up from scratch: sign up for a free trial at /signup, generate a CI-scoped key from the dashboard, and follow /docs/quickstart to get your first authenticated request working locally before wiring it into your pipeline. From there, /docs/messages covers the request schema you'll be asserting against, and /docs/streaming documents the event format if your contract tests need to cover streamed responses.
Questions
Do I need to test streaming responses differently in CI? Yes — streaming returns a sequence of events rather than one JSON body, so your test needs to collect chunks and assert on the final assembled text or specific event types, not just the HTTP response. See /docs/streaming for the event format.
Should CI tests use the same API key as production? No. Use a separate key scoped for testing so you can monitor and revoke CI usage independently, and so a bad test run can't exhaust your production rate limit or quota.
How many live API calls should a CI pipeline make per run? Keep it minimal — five to ten contract tests on merges to main plus one or two smoke tests post-deploy is typically enough. Everything else should run against mocked responses in unit tests.