Testingadvanced
Write consumer-driven contract tests (Pact)
Contract Test Writer
Write consumer-driven contract tests (Pact)
Write consumer-driven contract tests using Pact.
Instructions
- Install Pact:
npm install -D @pact-foundation/pact
- Consumer test (frontend/calling service):
import { PactV3 } from '@pact-foundation/pact';
const provider = new PactV3({
consumer: 'FrontendApp',
provider: 'UserService',
});
describe('User API Contract', () => {
it('should return user by id', async () => {
provider
.given('user 1 exists')
.uponReceiving('a request for user 1')
.withRequest({ method: 'GET', path: '/api/users/1' })
.willRespondWith({
status: 200,
body: {
id: 1,
name: MatchersV3.string('Alice'),
email: MatchersV3.email(),
},
});
await provider.executeTest(async (mockServer) => {
const client = new UserClient(mockServer.url);
const user = await client.getUser(1);
expect(user.name).toBeDefined();
});
});
});
- Publish pact to broker, then verify on provider side.
When to Use
- Microservices architecture where teams own different services
- Frontend consuming backend APIs
- Any service-to-service communication