← Blog

Testing Claude API Calls in a CI/CD Pipeline

2026-11-23 · 5 min read · SubToAPI Team

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:

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:

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:

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.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →