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.
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.
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' });
});
}); ✓ tests/orders.pact.test.js (1 test)
✓ fetches an order
pacts/web-orders-api.json writtenexecuteTest 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.