Implement consumer-driven contract testing with Pact. Ensure API changes don't break consumers without running full integration tests.
## Task Consumer-driven contract testing between API consumer and provider using Pact. ## Requirements - Framework: Pact (PactJS for TypeScript) - Consumer: React frontend or API client - Provider: REST API ## Consumer Test ```typescript // Consumer defines expectations: describe("User API", () => { it("fetches user by ID", async () => { // Define the expected interaction await provider.addInteraction({ state: "user with ID 123 exists", uponReceiving: "a request for user 123", withRequest: { method: "GET", path: "/api/users/123", headers: { Authorization: "Bearer valid-token" }, }, willRespondWith: { status: 200, headers: { "Content-Type": "application/json" }, body: { id: like("123"), name: like("John Doe"), email: email(), createdAt: iso8601DateTime(), }, }, }); // Test consumer code against mock const user = await userClient.getUser("123"); expect(user.name).toBeDefined(); }); }); // → Generates a pact contract file (JSON) ``` ## Provider Verification ```typescript // Provider verifies it satisfies the contract: const opts = { provider: "UserAPI", providerBaseUrl: "http://localhost:3000", pactUrls: ["./pacts/frontend-UserAPI.json"], stateHandlers: { "user with ID 123 exists": async () => { await db.user.create({ data: { id: "123", name: "John", email: "john@test.com" } }); }, }, }; await new Verifier(opts).verifyProvider(); ``` ## Implementation Notes 1. Consumer publishes pact to Pact Broker (or Pactflow) 2. Provider CI verifies against latest consumer pacts 3. Can I Deploy: check Pact Broker before deploying either service 4. Matchers: use like(), eachLike(), regex() — not exact values 5. Provider states: set up test data for each scenario 6. Versioning: tag pacts with consumer version and branch
No gallery images yet.