QA Interview Hub · Knowledge base · Quizzes · Українська

API › Contract testing in practice

Pact JS/TS: an example, matchers and what not to put in a contract

A Pact contract describes the response shape through matchers, not exact values: like checks the type, eachLike an array, regex a string against a pattern. The consumer test runs real client code, and the contract holds only fields the client reads and only errors it handles. Business logic stays out of the contract: otherwise verification fails without a real break, and the team stops trusting Pact.

API · Contract testing in practice

A Pact test fails every time the provider changes a value. What is wrong with the contract?

The provider refreshed its test data and the verification is red: the contract records "total": 150 and now it is 175. There is no real breakage, the API works as before. After the third such case the provider team starts ignoring Pact. This loss of trust is a heavier consequence than a missed bug. The lesson shows how to write a consumer test that tells "shape" from "value" and what is better left out of a contract.

How it works and why it is designed so

An example consumer test in Pact JS (the @pact-foundation/pact package, the PactV3 API; for new tests the Pact JS docs recommend PactV4, exported as Pact, with the same idea):

import { PactV3, MatchersV3 } from '@pact-foundation/pact';
const { like, eachLike, regex } = MatchersV3;

const pact = new PactV3({ consumer: 'web-app', provider: 'orders-api' });

it('returns an order by id', async () => {
  pact
1    .given('order 42 exists')
    .uponReceiving('a request for order 42')
    .withRequest({ method: 'GET', path: '/orders/42' })
    .willRespondWith({
      status: 200,
      headers: { 'Content-Type': 'application/json' },
      body: {
2        id: like(42),
        status: regex('NEW|PAID|SHIPPED', 'NEW'),
3        items: eachLike({ sku: like('A-1'), qty: like(1) }),
      },
    });

  await pact.executeTest(async (mockServer) => {
4    const order = await new OrdersClient(mockServer.url).getOrder(42);
    expect(order.items.length).toBeGreaterThan(0);
  });
});
  1. The provider state: before verification the provider brings the system to "order 42 exists".
  2. like(42): the type (a number) is checked, not the value 42.
  3. eachLike: an array of at least one element of this shape.
  4. The real client code hits the mock server: the test checks that the client parses the response.

Matchers. An example value in a contract does not mean "must be exactly this". like(x) checks the type, eachLike(template) an array with at least one element of that shape, regex(pattern, example) a string by a pattern, and there are also integer, datetime, uuid. Without matchers Pact compares values literally, and the provider fails on every data change.

The consumer test must run the real client code (the HTTP client, parsing), not check the mock itself. The goal is simple: if the client expects a field, it is in the contract; if the client does not read it, it is not.

Worked example: from a brittle contract to a thin one

One contract in two versions

Too tight

Exact values and extra fields

total: 150, every field of the response, the order of elements. The provider fails on every data change and the team stops trusting the tests.

Sufficient

The type and shape of what the client reads

total: like(150) and only the fields the client really uses. A change in data does not break verification, a change in shape does.

Figure 1. A brittle contract breaks with no real breakage and costs trust in the tests.

The diagnosis is simple: in the verification report the difference concerns a value (150 versus 175) with the type unchanged. The fix: replace the literal with a matcher and remove the fields the client code does not read. After that the verification fails only where the client would really break: a field disappeared or changed type.

What NOT to put in a contract

  • Business logic and exact values. The contract says "total is a number", not "total = 150 for this cart". Logic is checked by the provider's functional tests.
  • Fields the consumer does not use. Extra fields tie the provider down for no gain and get in the way of its refactoring.
  • All error codes "just in case". Only those the client really handles (404, 409, 422 with an error body).
  • UI details. A test through the browser instead of the client layer makes the contract slow and brittle.

A useful rule: "write the contract as an acceptance test of the consumer's need", not as a copy of the provider's response.

Common mistakes

  • Literals instead of matchers: verification fails on data changes.
  • The test checks the mock, not the client: the contract is "green" while a client that parses the response wrongly is not caught.
  • Copying the provider's whole response as the contract: extra fields and exact values.

Check yourself

The contract has status: regex('NEW|PAID|SHIPPED', 'NEW'). The provider added a CANCELLED status. Will the verification fail?

Answer

Only if the real response during verification contains CANCELLED: then the value does not match the pattern. That is the right signal if the client cannot handle the status, so before adding a new value you check who reads it.

Why must the consumer test call the real client code rather than just send a request to the mock?

Answer

The contract should reflect what the client really reads. If the test does not go through the client code, the contract holds what the author "thinks is needed", and nobody checks how the client parses the response.

In an interview. Junior: In the contract I describe the request and the shape of the response through matchers: like for a type, eachLike for an array. I do not fix exact values. Middle/Senior: The consumer test goes through the real client code, and the contract holds only the fields the client reads and only the errors it handles. Business logic stays with the provider's functional tests. That keeps the team's trust: a red Pact means a real breakage.

More articles in this chapter