Skip to content
jshacks.dev
Testing

Write a contract test with Pact

Record what a client expects from an API as a Pact file with PactV3 and a mock server, so the provider can be verified against it later.

2 min read
Summarize in AI

You want to know that the orders API still answers the way your web client expects, without running both together. A consumer contract test records the client's expectations against a mock server and writes them to a file.

tests/orders.pact.test.jsJavaScript
import path from 'node:path';
import { test, expect } from 'vitest';
import { PactV3, MatchersV3 } from '@pact-foundation/pact';
import { getOrder } from '../src/orders-client.js';

const provider = new PactV3({
  consumer: 'web',
  provider: 'orders-api',
  dir: path.resolve(process.cwd(), 'pacts'),
});

test('fetches an order', async () => {
  provider
    .given('order 7 exists')
    .uponReceiving('a request for order 7')
    .withRequest({ method: 'GET', path: '/orders/7' })
    .willRespondWith({
      status: 200,
      headers: { 'Content-Type': 'application/json' },
      body: { id: MatchersV3.integer(7), status: MatchersV3.string('paid') },
    });

  await provider.executeTest(async (mockServer) => {
    const order = await getOrder(mockServer.url, 7);
    expect(order).toEqual({ id: 7, status: 'paid' });
  });
});
Text
 ✓ tests/orders.pact.test.js (1 test)
   ✓ fetches an order

pacts/web-orders-api.json written

executeTest starts a mock server that only answers the declared interaction, runs your client against it, then writes the contract to pacts/web-orders-api.json. Matchers say that any integer or string is acceptable, so the provider is not forced to return exactly 7 and paid. The provider side replays this file with the verifier, described in the Pact JS docs.

Use it when two teams deploy separately. A contract test says nothing about behaviour behind the endpoint, so it does not replace tests of the provider's own logic.

Taggedpact
Share

More snippets

Debugging

Debug a single Vitest test in VS Code

Run one Vitest file under the VS Code debugger with a launch configuration that passes the open file, so breakpoints in tests and source work. Vitest 3.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.