SyntaxStudy
Sign Up
REST API Contract Testing with Pact
REST API Beginner 1 min read

Contract Testing with Pact

Contract testing verifies that two services (consumer and provider) agree on the API contract. Unlike integration tests that require both services running simultaneously, Pact captures the consumer's expectations as a JSON pact file and verifies them independently against the provider. This makes contract testing fast, reliable, and suitable for CI pipelines. Consumer-driven contract testing means the consumer defines what it needs (specific fields, status codes, types) and the provider verifies it can satisfy those expectations. When a provider change would break a consumer, the CI pipeline catches it before deployment—without any end-to-end environment.
Example
// npm install @pact-foundation/pact

// Consumer test (frontend / API client)
import { Pact } from '@pact-foundation/pact';
import { like, eachLike, term } from '@pact-foundation/pact/src/dsl/matchers';

const provider = new Pact({
  consumer: 'WebApp',
  provider: 'ProductsAPI',
  port: 1234,
  log: './pacts/logs/pact.log',
  dir: './pacts',
});

describe('Products API contract', () => {
  before(() => provider.setup());
  after(() => provider.finalize());

  it('returns a list of products', async () => {
    await provider.addInteraction({
      state: 'products exist',
      uponReceiving: 'a request for products',
      withRequest: { method: 'GET', path: '/api/v1/products',
                     headers: { Authorization: like('Bearer token') } },
      willRespondWith: {
        status: 200,
        body: {
          data: eachLike({
            id:    like(1),
            name:  like('Running Shoes'),
            price: like(89.99),
          }),
          meta: { total: like(10) },
        },
      },
    });

    const products = await fetchProducts('Bearer token');
    expect(products.data[0]).toHaveProperty('name');
  });
});

// Provider verification (in ProductsAPI CI)
// const { Verifier } = require('@pact-foundation/pact');
// new Verifier({ provider: 'ProductsAPI', pactUrls: ['./pacts/WebApp-ProductsAPI.json'],
//   providerBaseUrl: 'http://localhost:8000' }).verifyProvider();

This is the last lesson in this section.

Create a free account to earn a certificate