17 / 89 · 04 API & Contract Testing with AI · Consumer-Driven Contract Testing with Pact← prev⊞ allnext →☰ Read as one page
3.5Writing Consumer Tests
JavaScript/TypeScript with Pact V4
import { PactV4, MatchersV3 } from '@pact-foundation/pact';
const { like, eachLike, uuid, decimal, term } = MatchersV3;
const provider = new PactV4({
consumer: 'StorefrontUI',
provider: 'ProductService',
});
describe('ProductClient Pact Tests', () => {
describe('getProduct', () => {
it('returns a product when it exists', async () => {
await provider
.addInteraction()
.given('product ABC-123 exists')
.uponReceiving('a request for product ABC-123')
.withRequest('GET', '/api/v2/products/ABC-123', (builder) => {
builder.headers({ Authorization: like('Bearer valid-token') });
})
.willRespondWith(200, (builder) => {
builder.jsonBody({
id: uuid(),
name: like('Blue Widget'),
price: decimal(29.99),
category: term({
generate: 'electronics',
regex: 'electronics|clothing|food|other'
}),
in_stock: like(true),
});
})
.executeTest(async (mockServer) => {
const client = new ProductClient(mockServer.url, 'valid-token');
const product = await client.getProduct('ABC-123');
expect(product.name).toBeDefined();
expect(product.price).toBeGreaterThanOrEqual(0);
});
});
it('returns 404 when product does not exist', async () => {
await provider
.addInteraction()
.given('product NONEXISTENT does not exist')
.uponReceiving('a request for a nonexistent product')
.withRequest('GET', '/api/v2/products/NONEXISTENT', (builder) => {
builder.headers({ Authorization: like('Bearer valid-token') });
})
.willRespondWith(404)
.executeTest(async (mockServer) => {
const client = new ProductClient(mockServer.url, 'valid-token');
await expect(client.getProduct('NONEXISTENT'))
.rejects.toThrow();
});
});
});
});
Python with Pact
from pact import Consumer, Provider
pact = Consumer('InventoryDashboard').has_pact_with(
Provider('ProductService'),
pact_dir='./pacts'
)
def test_get_product():
expected_body = {
"id": Term(r'^[a-f0-9-]{36}$', "550e8400-e29b-41d4-a716-446655440000"),
"name": Like("Blue Widget"),
"price": Like(29.99),
"category": Term(r'^(electronics|clothing|food|other)$', "electronics"),
}
(pact
.given("product exists")
.upon_receiving("a request for a product")
.with_request("GET", "/api/v2/products/550e8400-e29b-41d4-a716-446655440000")
.will_respond_with(200, body=expected_body))
with pact:
result = ProductClient(pact.uri).get_product(
"550e8400-e29b-41d4-a716-446655440000"
)
assert result["name"] is not None
assert result["price"] >= 0