Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
API testing APIs APIs From Zero to Real-World API Testing & Automation contract testing Module 6 — API Testing

Contract Testing and Integration Testing for APIs

Reviewed & accurate
AI Summary

What You'll Learn

  • What contract testing is and why it exists
  • What integration testing covers
  • How to use tools like Pact for contract testing
  • When to use each type of test

Why This Matters

Modern apps are built from many services talking to many APIs. Unit tests verify each service in isolation. But the bugs live at the seams — when service A calls service B and B's response has changed in a way A does not expect. Contract and integration testing target these seams. Without them, you find integration bugs in production, at 3 AM, on a Friday.

The Problem These Tests Solve

Imagine: your frontend calls your backend. Your backend calls a payments API. The payments API silently changes a field name from transaction_id to txn_id. Unit tests on your backend still pass (you mocked the payments API). Integration tests on your backend still pass (you mocked the payments API). The bug only surfaces in production — when real users try to pay and your backend cannot find transaction_id in the response.

Contract testing catches this. The payments API's contract says "the response includes transaction_id". When they change it to txn_id, the contract test fails — even though no real request has been made yet.

What Is Contract Testing?

Contract testing verifies that two services agree on the format of their communication. The consumer (caller) defines what it expects. The provider (callee) verifies it still produces that. If either side changes without the other updating, the test fails.

Consumer-driven contract testing

The most common style. The consumer writes a "contract" describing what it expects from the provider. The provider runs the contract against its own API to verify compliance.

How Pact works (the most popular tool)

  1. Consumer writes tests that mock the provider's responses. Pact records these as a "contract" file.
  2. Contract is shared with the provider (via Pact Broker or direct file).
  3. Provider runs the contract against its real API. If the provider's response does not match what the consumer expects, the test fails.

Example Pact consumer test (JavaScript)

const { Pact } = require("@pact-foundation/pact");

const provider = new Pact({
  consumer: "FrontendApp",
  provider: "UserAPI"
});

describe("User API", () => {
  before(() => provider.setup());
  after(() => provider.finalize());

  it("gets a user by ID", async () => {
    // Define the expected interaction
    await provider.addInteraction({
      uponReceiving: "a request for a user",
      withRequest: {
        method: "GET",
        path: "/users/123"
      },
      willRespondWith: {
        status: 200,
        headers: {"Content-Type": "application/json"},
        body: {
          id: 123,
          name: "Anita",
          email: "anita@example.com"
        }
      }
    });

    // Make the real request to the mock provider
    const user = await getUser(123);
    expect(user.name).toBe("Anita");
  });
});

Pact generates a contract file from this test. The provider then verifies it produces the same response shape.

What Is Integration Testing?

Integration testing verifies that multiple components work together. For APIs, this usually means testing a flow that crosses multiple endpoints or services.

Example integration test — user signup flow

describe("User signup flow", () => {
  let token;
  let userId;

  it("registers a new user", async () => {
    const res = await request
      .post("/api/register")
      .send({email: "anita@example.com", password: "Secret123!"});

    expect(res.status).toBe(201);
    userId = res.body.id;
  });

  it("logs in the new user", async () => {
    const res = await request
      .post("/api/login")
      .send({email: "anita@example.com", password: "Secret123!"});

    expect(res.status).toBe(200);
    token = res.body.access_token;
  });

  it("fetches the user profile with the token", async () => {
    const res = await request
      .get("/api/users/me")
      .set("Authorization", `Bearer ${token}`);

    expect(res.status).toBe(200);
    expect(res.body.id).toBe(userId);
    expect(res.body.email).toBe("anita@example.com");
  });

  it("deletes the user (cleanup)", async () => {
    const res = await request
      .delete(`/api/users/${userId}`)
      .set("Authorization", `Bearer ${token}`);

    expect(res.status).toBe(204);
  });
});

This tests the integration of registration, login, authenticated fetch, and deletion — a real user flow.

Contract Testing vs Integration Testing

AspectContract testingIntegration testing
TestsThe agreement between consumer and providerThe actual flow across endpoints
Runs againstMocked provider (consumer side), real provider (provider side)Real services
SpeedFastSlower (real network, real DB)
CatchesSchema/format driftEnd-to-end flow bugs
When to useMicroservices, third-party APIsCritical user flows

When to Use Each

SituationUse
Frontend calling your backendContract testing
Your backend calling another internal serviceContract testing
Your backend calling a third-party APIContract testing (if they support it) + smoke tests
Critical user flows (signup, checkout)Integration testing
Multiple services working togetherBoth

Common Mistakes

  1. Using only integration tests. They are slow and brittle. Use contract tests for the seams, integration tests for the critical flows.
  2. Mocking everything in integration tests. If you mock the database and the external APIs, you are writing unit tests, not integration tests.
  3. Not cleaning up after integration tests. Each run leaves data in the database. Use teardown hooks to delete test users, orders, etc.
  4. Contracts that are too strict. Requiring exact values (not just structure) makes contracts brittle. Test the shape, not the data.
  5. Not running contract tests in CI. Contracts only catch drift if they run on every change.

Practical Exercise (20 minutes)

  1. Pick a multi-step flow on JSONPlaceholder (e.g., create a post, then list posts by that user, then delete the post).
  2. Write an integration test in JavaScript or Python that exercises the full flow.
  3. Use the response from each step as input to the next.
  4. Clean up at the end (delete what you created).

Mini Challenge

Design a contract test for an API you consume. Write down: (1) what does the consumer expect from the provider? (2) what fields are required? (3) what fields are optional? (4) what types? (5) what would break the consumer if the provider changed it? This is the contract.

Key Takeaways

  • Contract testing verifies two services agree on the format of their communication.
  • Integration testing verifies multiple endpoints work together in a real flow.
  • Use contract tests for microservice seams. Use integration tests for critical user flows.
  • Contracts should test the shape (structure), not exact values.
  • Run both in CI — they only catch drift if they run on every change.
Course continuity
Previously: Lessons 32–35 covered testing concepts.
Today: You learned to test the seams between services.
Next: Module 6 is complete. Module 7 begins with lesson 37 — Postman Collections, Folders, and Environments.

FAQ

Can I do contract testing without Pact?

Yes. You can write your own contract tests using JSON Schema and a shared schema file. Pact is the most popular tool, but the concept matters more than the tool. Some teams use OpenAPI specs as contracts.

How is integration testing different from end-to-end testing?

Integration testing verifies a few components together (e.g., API + database). End-to-end testing verifies the entire system from user action to final response (e.g., browser → frontend → backend → database → response). E2E is slower and more brittle; use it sparingly.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments