Skip to content

    Frontend System Design

    Contract Testing for Front Ends

    Let a front end write down exactly what it needs from an API, replay that against the real service, and catch a breaking change before it ships, with a lab.

    By Published 13 min read

    • frontend-system-design
    • contract-testing
    • testing
    • api-contracts
    Share

    Standard lessonadvancedTypeScript labFrontend System Design

    Before this: Integration Testing With Network Mocking, API Contracts and Data Transformation

    What you'll learn: By the end of this lesson you will be able to explain why a mocked API test can pass while the real API has changed, describe a consumer-driven contract (interactions, matchers, provider states), say why requests are matched strictly and responses loosely, tell what a contract should leave out, read a verification failure by its path, and use a verification matrix to decide whether a front end and an API version may go live together.

    Think of two companies that agree on a pallet size. The shop writes on a card: "we need boxes that fit on a standard pallet, with a label on the short side". The supplier checks every new box design against the card before it leaves the factory. Neither side reads the other's whole catalogue. The card is small, it was written by the party that depends on it, and it is checked automatically each time something changes. That card is a contract.

    The running example is the product page of the ShopStream storefront and the product API behind it. The page shows a name, a price and a currency, and later a discount. The names, prices and states in the lab are made up for the lesson.

    The core idea

    1. A test that mocks the API only proves the front end agrees with the mock. The mock is written by the front end's team, so it can be wrong in the same way the code is wrong, and it stays right when the real API moves.
    2. A consumer-driven contract writes the mock down as a file and makes the provider prove it. The front end's tests record each request it makes and the least it needs back. The API's build replays those requests against the real service.
    3. The contract is the need, not the API. It lists only what this consumer reads. Everything else the provider sends is free to change.

    Three illustrations run through the lesson: a minimal example (one recorded interaction), a realistic example (the product page growing a discount field) and a failure example (a renamed price field).

    Why the mock drifts

    In an integration test with network mocking (a separate lesson in this module), a front end test answers HTTP calls with canned responses. That is fast and deterministic, and it has one blind spot: nobody checks the canned response against the service. If the provider renames price_cents to priceCents, every front end test stays green and the page shows "NaN" in production.

    Generated types (From OpenAPI to TypeScript Contract Types) do not check the running service, and a run-time edge (API Contracts and Data Transformation) fails safely only after the change shipped. A contract test finds the break before either side deploys.

    What a contract is

    Ian Robinson separates three ideas. A provider contract describes everything a service offers; it is closed and complete. A consumer contract is the set of expectations one consumer has, and it is open and incomplete, because it covers only that consumer. A consumer-driven contract is what a provider ends up with when it accepts the union of its consumers' expectations.

    In practice, the contract is a list of interactions. Each one holds:

    Part What it says Example from the lab
    Description A name for the scenario a request for product p-100
    Provider state A precondition on the provider's data product p-100 exists
    Request Method, path, query, headers, body GET /products/p-100 with accept: application/json
    Response Status, headers and the least body needed 200, a name that is a string, a price that is an integer

    Figure 1. Where a contract comes from and where it goes

    Consumer tests record a contract against a mock; the provider's build replays it against the real serviceFront end test to Mock provider (request); Mock provider to Contract (if test passes); Contract to Verification (shared); Verification to Real provider (replay)FRONT END BUILDAPI BUILDFront end test: real client codeFront end testreal client codeMock provider: answers examplesMock provideranswers examplesContract: JSON fileContractJSON fileVerification: replays requestsVerificationreplays requestsReal provider: state set up firstReal providerstate set upfirstrequestif test passessharedreplay

    How to read this: the left half runs in the front end's pipeline and produces a file. The right half runs in the provider's pipeline and reads that file. The only thing they share is the contract.

    The Pact documentation describes the same flow. The consumer registers the expected request and response with a mock service, the consumer test sends a real request to it, and when all interactions pass the framework writes a pact file. In the provider phase each recorded request goes to the real provider, and verification passes if each response contains at least the data the consumer described.

    Matching: strict requests, loose responses

    Contract tests compare values, and the rules about how strictly decide whether the suite is useful or brittle. The Pact docs give a clear rule. For requests, prefer exact matching, since the consumer controls the data; extra JSON body fields and extra query parameters are not allowed, though extra headers are. For responses, be as loose as possible: unexpected values in a JSON response body are ignored during provider verification, and matchers are used only where a format matters.

    Matcher (lab name) Means The mock returns Verification checks
    A plain value Exactly this That value Equal
    like(example) Something of this type The example Same JSON type, recursively
    integer(example) Any integer The example Number.isInteger
    regex(pattern, example) A string in this format The example A string matching the pattern
    eachLike(example, min) A list of such items min copies At least min items, each matching

    The lab's matchers model the idea and borrow Pact's names. In the Pact docs, type matching returns the example to the consumer test but verifies only the type, a regular expression pairs a sample with a pattern, and eachLike checks each element against a template and requires at least one element.

    Figure 2. One expectation, used twice

    flowchart LR accTitle: One expectation used on both sides accDescr: An expectation such as a price that is an integer with example 1250 is written once in the consumer test. The mock turns it into the example value 1250 for the consumer's code. The provider verification checks that the real value is an integer. If the real value is the string 12.50 the verification fails with a path. E["Expectation
    price_cents: integer(1250)"] --> M["Mock returns
    1250"] E --> V["Verification checks
    is it an integer?"] M --> C["Consumer code
    runs on an example"] V --> R{"Real value"} R -->|"1250"| P["pass"] R -->|"string 12.50"| F["fail: body.price_cents"]

    How to read this: the same line feeds the consumer's test and the provider's check. That is why the example must be a value the consumer's code can really work with.

    Provider states

    An interaction like "get product p-100" only makes sense if p-100 exists. A provider state names that precondition. The Pact docs call states "the necessary preconditions for a particular test scenario to run", name the state in the consumer's given clause, and use the name to find the block of provider code that sets up the data. Each interaction in a pact should be verified in isolation, with no context kept from earlier ones.

    The lab's provider has one handler per state name. A state with no handler fails that interaction, with the message no handler for provider state. That rule is this lab's choice.

    What a contract should leave out

    A contract test is not a functional test. The Pact guidance says contract tests focus on the messages that flow between consumer and provider, do not check side effects, and should not "dig into the business logic of the Provider". It also warns that many validation scenarios create "an unnecessarily tight contract" that blocks the provider from loosening rules even when that is not a breaking change. For invalid input, write one scenario that expects a 400 and any error string, not one per rule.

    For a front end: one interaction per call shape the page makes, the fields it reads, and the error forms it branches on. Price rules and validation messages belong in the provider's own tests.

    Illustration 1 (minimal example): one interaction

    The lab's first interaction, shown as stored in the contract (a JSON file, matchers as tagged objects):

    Expected output, captured from a real run (the first nine lines of the lab's demo):

    === 1. Consumer tests write the contract
    consumer: product-page 1.0, provider: product-api, interactions: 3
    - GET /products/p-100 -> 200 (given: product p-100 exists)
    - GET /products/p-999 -> 404 (given: product p-999 does not exist)
    - GET /products?category=mugs -> 200 (given: category mugs has products)
    expected body of the first interaction, as stored:
    {"id":"p-100","name":{"$matcher":"like","example":"Trail mug"},"price_cents":{"$matcher":"integer","example":1250},"currency":{"$matcher":"regex","pattern":"^[A-Z]{3}
    quot;,"example":"EUR"}} survives a JSON round trip: true release 1.1 adds one interaction: 4 in total

    The id is a plain value because the request fixes it. The name is only a like, because the page shows whatever string it gets. The price is an integer, because the page does arithmetic on it. Nothing about category or any other field the page ignores appears.

    In Pact JS the same interaction is written as a chain (addInteraction, given, uponReceiving, withRequest, willRespondWith, executeTest), and executeTest hands your test a mock server URL. The lab is a model, so no Pact package is installed or run here; take the exact calls from the Pact JS guide for the version you install.

    Verification and the matrix

    When the provider's build replays the contract, each interaction produces either a pass or a list of mismatches with a path. Fixing a failure then means reading one line: body.price_cents: missing property.

    Figure 3. A change reaches production only through a verified pair

    sequenceDiagram accTitle: Verification before deploy accDescr: The front end pipeline runs its contract tests and publishes the contract with its version. The provider pipeline fetches the contract, replays it against the new provider version and publishes the result. Before deploying either side, a can-I-deploy check asks the broker whether a successful verification exists for that pair of versions. If not, deployment stops. participant F as Front end pipeline participant B as Contract store participant P as Provider pipeline F->>B: publish contract (front end version) P->>B: fetch contracts P->>P: replay against new provider version P->>B: publish result (provider version) F->>B: can I deploy this front end version? B-->>F: yes only if a passing result exists for the pair

    How to read this: neither side calls the other. A shared store holds contracts and results, and "can I deploy" is a question to that store.

    The Pact Broker's can-i-deploy works this way: it checks that a successful verification result exists between the version you want to deploy and the versions already in the target environment, and it exits with code 0 for yes and 1 for no. Its matrix lists the consumer and provider versions that have been tested against each other and whether each passed. The lab models the same question with an invented, simpler rule: a pair is safe only if a passing result exists for exactly that pair.

    Illustration 2 (realistic example): the page asks for a discount

    Release 1.1 of the product page shows a discounted price. It adds one interaction with the state product p-101 has a 10 percent discount and a body with discount_percent: integer(10). The provider has not shipped the field yet.

    Expected output, captured from a real run (provider variants against the new contract, plus the final matrix):

    === 5. The consumer asks for something new (release 1.1 needs discount_percent)
    --- provider v1 -> verified: false
      [FAIL] a request for a product with a discount
             body.discount_percent: missing property
    --- provider discounts -> verified: true
    release 1.1 against provider discounts: discountPercent 10

    The front end started the change. The provider team sees a failing verification that names the field and the state. The matrix then records which pairs may go live:

    Expected output, captured from a real run (the lab's matrix; versions and results are the lab's own):

    === 7. Verification matrix and can-i-deploy
    provider    web-1.0  web-1.1
    api-1       pass     FAIL
    api-2       pass     FAIL
    api-3       FAIL     FAIL
    api-4       FAIL     FAIL
    api-5       FAIL     FAIL
    api-6       pass     pass
    can web-1.1 go live with api-1? no (verification failed)
    can web-1.1 go live with api-6? yes (verified)
    can web-1.0 go live with api-3? no (verification failed)
    can web-1.0 go live with api-7? no (no verification result)

    Release 1.0 passes against api-2, which only added fields, so additive changes cost the provider nothing. And api-7 has no result: absence of a failure is not a pass.

    Illustration 3 (failure example): a rename, a retype, a changed error

    Expected output, captured from a real run (the lab replays contract 1.0 against four changed providers):

    === 4. Provider changes, replayed against contract 1.0
    --- additive: adds created_at and warehouse_code -> verified: true
    --- rename: renames price_cents to priceCents -> verified: false
      [FAIL] a request for product p-100
             body.price_cents: missing property
      [FAIL] a request for the mugs category
             body.items[0].price_cents: missing property
             body.items[1].price_cents: missing property
    --- retype: sends price_cents as a decimal string -> verified: false
      [FAIL] a request for product p-100
             body.price_cents: expected an integer, got string "12.50"
      [FAIL] a request for the mugs category
             body.items[0].price_cents: expected an integer, got string "12.50"
             body.items[1].price_cents: expected an integer, got string "4.05"
    --- error-shape: changes the 404 body to an error string -> verified: false
      [FAIL] a request for a product that does not exist
             body.code: missing property
             body.message: missing property
    --- reworded: same shape, different product names -> verified: true

    The rename and the retype are the breaking changes that API Contract Evolution for Clients sorts into compatible and breaking. The error body is the quiet one: the page branches on code, so the contract pins it, and the consumer's own test could never have noticed the provider moving it. The reworded provider changes names and nothing else, and it passes, which is the point of like.

    The opposite mistake is to over-specify. The lab runs the same interaction twice against reworded:

    Expected output, captured from a real run (the same interaction written two ways):

    === 6. Over-specified: pinning the name makes a harmless change a failure
    like(name) against reworded: verified true
    exact name against reworded: verified false (body.name: expected "Trail mug", got string "Trail mug, 350 ml")

    A contract that pins data the page does not depend on turns a harmless change into a provider build failure, and teams learn to ignore the check.

    Choosing

    Choice Gain Cost
    Consumer-driven contracts Each consumer's real need is checked; additive changes stay free A contract store, versioning, provider state handlers, and a process between teams
    Provider checked only against its OpenAPI file One source of truth, no consumer tooling Does not say who reads which field, so a removal looks safe until a page breaks
    End-to-end tests only Real behaviour Slow, flaky, and a failure rarely names the changed field

    Build it: record, verify and ask "can I deploy"

    Goal. Run a model of consumer-driven contract testing end to end: write a contract from consumer tests, verify seven provider variants, and ask a matrix whether a pair may go live.

    Setup. The lab is in the course's example workspace (Node 26.13.1, pnpm). It is pure TypeScript, with no HTTP, no browser and no Pact package.

    cd examples/frontend
    pnpm install
    cd labs/consumer-contract-testing
    pnpm test           # 24 tests
    node src/demo.ts

    Steps.

    1. Run the tests, then the demo, and compare section 1 with the output above.
    2. In section 2 of the demo, a consumer test with the wrong path, an extra query parameter and a missing header fails, and the contract stays empty.
    3. For each failing line in sections 4 to 6, find the matcher in src/consumerTests.ts that produced it.

    What the lab does not show. It does not follow the Pact file format or Pact's matching code, runs no HTTP server and has no broker; "can I deploy" is a one-rule model. How Pact itself behaves is taken from its documentation, not from this lab.

    Break it. In src/matchers.ts, in check, change the like case to return check(m.example, actual, path);. like now compares values and not types, eight tests fail (including "additive changes and different data pass"), and the reworded provider is rejected. Revert it.

    In practice: a price field that broke the cart

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    A storefront's product page, cart widget and mobile web view all call one product API owned by another team. The API team wants to move prices from integer minor units to a decimal string "to be friendlier". The front end teams hear about it a week before the release.

    Starting architecture

    Figure 4. Starting point: three consumers, one provider, no shared check

    Starting architecture: three front ends call one API, and the API team cannot see which fields they readProduct page to Product API (GET product); Cart widget to Product API (GET product); Mobile web to Product API (GET list)Product page: reads priceProduct pagereads priceCart widget: sums pricesCart widgetsums pricesMobile web: reads nameMobile webreads nameProduct API: other teamProduct APIother teamGET productGET productGET list

    How to read this: the provider sees three callers but not what each one reads. A rename or retype looks safe from the provider's side.

    Options considered

    Option What it fixes What it costs Risk
    Each consumer adds a contract, provider verifies in CI Each break is named by path before release A contract store, state handlers, and a habit of writing small contracts Over-specified contracts create noise

    The decision

    Field Decision record
    Context One provider, three front ends, release schedules that do not line up.
    Decision Each front end records contracts for the calls it makes, with like, integer and regex for values and plain values for the fixed request. The provider verifies every consumer's latest contract in CI, and each side runs can-i-deploy before release.
    Consequences, good A breaking change fails the provider build with a path and the consumer's name. Additive changes keep passing.
    Consequences, bad Contract upkeep and a shared store to run.
    Revisit when Consumers outnumber what the team can maintain, or a typed description of the API makes a lighter check enough.

    Rollout and verification

    1. Start with one consumer and the three calls that matter, not every call. Keep matchers loose.
    2. Run verification as a non-blocking job first, then make it blocking and add can-I-deploy to both pipelines.

    The 2 a.m. failure

    A provider release ships and the cart total shows "NaN". The cart widget has no contract yet, so verification passed. Support reports it within minutes (illustrative).

    First three checks: (1) compare the failing response with what the widget reads; (2) check whether the widget's calls appear in any contract; (3) check whether the provider's verification includes every current consumer. Mitigation: roll the provider back, or add a compatibility field while the widget is fixed. Follow-up: record the widget's contract, make "has a contract" part of onboarding a new front end, and keep run-time response validation in the widget as the last line of defence.

    The other side of this topic

    The back end has the same practice from the provider's seat: verifying published contracts in its pipeline and writing state handlers. A back end lesson covers Pact and Spring Cloud Contract; this one stays with what the consumer writes.

    Architect's notes

    • Write the contract from the need. Record only the fields and calls the page uses.
    • Loose responses, strict requests. Use matchers for values; pin only what identifies the call.
    • Treat a missing result as a no. "Not verified" is not "verified".
    • Keep functional checks on the provider's side. Rules and side effects belong in its own tests.

    Common mistakes

    • Pinning exact data the page does not depend on.
    • Testing business rules through the contract, one scenario per rule.
    • Mocking by hand and calling it a contract: nothing makes the provider prove it.

    Key takeaways

    • A mock proves the front end matches the mock. A contract makes the provider prove the same expectation.
    • The contract is the consumer's need: extra provider fields are ignored in responses; requests are matched strictly.
    • Provider states set up the data each interaction needs, and each interaction is verified alone.
    • Keep contracts about messages, not business rules or side effects.
    • A failure names a path: read body.price_cents: missing property as the fix.
    • Can I deploy needs a passing result for the exact pair; no result means no.

    Practice exercises

    Exercise 1 — Starter (45 min): List every call one page of your own app makes. For each, write the interaction as a table: state, request, and only the response fields the page reads.

    Exercise 2 — Intermediate (2 hours): In the lab, add an interaction for POST /cart with a state and a 201 response, a provider handler, and a variant that breaks it.

    Exercise 3 — Advanced (half day): Write an over-specified contract, show a harmless provider change that fails it, then loosen it and state what you gave up.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments