Skip to article content
FrontendXLesson 12 / 24

Consumer-Driven Contract Testing

Build a working model of automated testing from assertions to unit, component, API, integration, contract and end-to-end tests, then apply it to a single progressive task-board capstone where each milestone adds a real defect, a failing test, a corrected implementation and an expected result.

advanced · about 45 minutes · 6 exercises

  • Predict
  • Explain
  • Implement
  • Debug
  • Test
  • Interview

What you will be able to do

#
  • Explain the problem contract testing solves between services.
  • Describe a consumer contract and how the provider verifies it.
  • Decide when a contract test is worth the setup cost.

Overview

#

The gap between services

When a frontend consumes an API, two teams can each pass their own tests while the integration is broken. The frontend mocks the API with the shape it expects. The API tests its own handlers. Neither test checks that the two agree. The break only appears in production or in a slow end-to-end run.

A contract is a shared expectation

A consumer-driven contract records what the consumer expects from the provider: the request it sends and the response it needs. The consumer generates this contract from its own tests. The provider then verifies that its real implementation satisfies every contract it has published.

snippet.json
{
  "description": "a request for user 7",
  "request": { "method": "GET", "path": "/api/users/7" },
  "response": { "status": 200, "body": { "id": 7, "name": "string" } }
}

Both sides run the same contract

The consumer test asserts against a mock built from the contract. The provider test replays the contract's requests against the real service and checks the responses. If the provider changes a field name, the provider's contract verification fails before deployment, and the failure names the consumer that would break.

Types versus values

A contract usually checks types and required fields, not exact values, so the provider keeps freedom over the data while guaranteeing the shape. id must be a number, name must be a string. Exact-value assertions belong in the provider's own tests, not in the cross-team contract.

When it is worth it

Contract testing pays off when multiple consumers depend on one provider and the teams deploy independently. For a single frontend and a single backend deployed together, an integration test against a real test backend is simpler and sufficient. Adopting a contract broker for a two-service system adds ceremony without much benefit. Match the tool to the coordination problem.

Capability note

A full contract workflow needs a broker or a shared artifact store and both services running their verification steps, which happens in CI. A browser sandbox cannot run a provider verification against a real service. State this boundary rather than simulating a pass.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    The provider renames `name` to `fullName`. What does the consumer contract verification report?

    Choose the best answer
  2. Exercise 2Explain

    Explain what breaks when two services have passing tests but no contract.

    Reveal the reference answer
    reference.javascript
    Each service tests against its own assumptions. The consumer mocks the API with the shape it expects, and the provider tests its handlers against its own fixtures. Neither test crosses the boundary, so a mismatch in field names, types or status codes is invisible to both suites. The integration is only exercised in production or in a slow end-to-end test, which is exactly the gap contract testing closes.

    The answer should identify the untested boundary as the shared blind spot and connect contracts to closing it.

  3. Exercise 3Implement

    Implement `verifyContract(response, contract)` that returns true when the response has every required field with the required type. `console.log(verifyContract({ id: 1, name: 'a' }, { id: 'number', name: 'string' }), verifyContract({ id: 1 }, { id: 'number', name: 'string' }))` should print `true false`.

    starter.javascript
    function verifyContract(response, contract) {
      // your code here
    }

    Reveal the reference answer
    reference.javascript
    function verifyContract(response, contract) {
      for (const [field, type] of Object.entries(contract)) {
        if (typeof response[field] !== type) return false;
      }
      return true;
    }

    Authored expected output: true false

    The verifier checks each required field's type. The first response satisfies both fields; the second is missing name, so typeof undefined is not 'string' and the check returns false.

  4. Exercise 4Debug

    This contract check passes even when a required field has the wrong type. Fix it so `console.log(verifyContract({ id: 'one' }, { id: 'number' }))` prints `false`.

    starter.javascript
    function verifyContract(response, contract) {
      return Object.keys(contract).every((field) => field in response);
    }
    console.log(verifyContract({ id: 'one' }, { id: 'number' }));

    Reveal the reference answer
    reference.javascript
    function verifyContract(response, contract) {
      return Object.entries(contract).every(([field, type]) => typeof response[field] === type);
    }
    console.log(verifyContract({ id: 'one' }, { id: 'number' }));

    Authored expected output: false

    Checking only key presence ignores type. A field present but of the wrong type still breaks the consumer. Comparing typeof against the declared type catches both a missing field and a wrong type.

  5. Exercise 5Test

    Write a test that proves `verifyContract` accepts a valid response and rejects a wrong-typed field.

    starter.javascript
    function verifyContract(response, contract) {
      for (const [field, type] of Object.entries(contract)) {
        if (typeof response[field] !== type) return false;
      }
      return true;
    }

    Reveal the reference answer
    reference.javascript
    function assertEqual(actual, expected, label) {
      if (actual !== expected) throw new Error(label + ': expected ' + expected + ' but got ' + actual);
    }
    const contract = { id: 'number', name: 'string' };
    assertEqual(verifyContract({ id: 1, name: 'a' }, contract), true, 'valid response');
    assertEqual(verifyContract({ id: '1', name: 'a' }, contract), false, 'wrong type rejected');
    assertEqual(verifyContract({ id: 1 }, contract), false, 'missing field rejected');
    console.log('contract verified');

    Authored expected output: contract verified

    The three assertions cover the valid case, a wrong type and a missing field. Together they prove the verifier enforces the contract rather than merely checking key presence.

  6. Exercise 6Interview

    In an interview, explain when you would introduce contract testing and when you would not.

    Reveal the reference answer
    reference.javascript
    I introduce it when several consumers depend on one provider and the teams deploy independently, because then a provider change can silently break a consumer that is not in the provider's test suite. I would not introduce it for a single frontend and backend deployed together, where an integration test against a real test backend is simpler and catches the same class of defect. The value scales with the number of independent consumers.

    The answer should tie the decision to independent deployment and multiple consumers, and should be willing to say no when the coordination problem is small.

Common misconceptions

#
  • Contract tests replace integration tests entirely.
  • A contract should assert exact response values.
  • Every project needs a contract broker.

Follow-up practice

#
  • testing-mutation
  • testing-capstone-quality-task-board

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.