22 / 89 · 04 API & Contract Testing with AI · AI-Enhanced Contract Generation and Maintenance← prev⊞ allnext →☰ Read as one page
4.2AI-Powered Contract Generation
The Prompt
Analyze this API client code and generate Pact consumer tests for every
external API call it makes.
```typescript
// services/product-client.ts
export class ProductClient {
constructor(private baseUrl: string, private token: string) {}
async getProduct(id: string): Promise<Product> {
const res = await fetch(`${this.baseUrl}/api/v2/products/${id}`, {
headers: { Authorization: `Bearer ${this.token}` }
});
if (!res.ok) throw new ApiError(res.status, await res.text());
return res.json();
}
async searchProducts(query: string, limit = 20): Promise<ProductList> {
const res = await fetch(
`${this.baseUrl}/api/v2/products?q=${encodeURIComponent(query)}&limit=${limit}`,
{ headers: { Authorization: `Bearer ${this.token}` } }
);
if (!res.ok) throw new ApiError(res.status, await res.text());
return res.json();
}
}
Generate Pact consumer tests using @pact-foundation/pact that:
- Define the expected request (method, path, headers, query params)
- Define the expected response shape (using Pact matchers for flexibility)
- Cover both success and error scenarios
- Use Pact matchers (like, eachLike, term) instead of exact values
### What AI Detects from Client Code
| Client Code Pattern | AI-Generated Contract |
|--------------------|-----------------------|
| `fetch(\`/api/v2/products/${id}\`)` | GET /api/v2/products/{id} interaction |
| `headers: { Authorization: \`Bearer ${token}\` }` | Auth header expectation |
| `if (!res.ok) throw new ApiError(...)` | Error scenario interactions |
| `res.json()` | JSON response body expectation |
| `query: string, limit = 20` | Query parameter expectations |
| `Promise<Product>` | Response body shape from Product type |