====== Pact contract test - Login API ======
===== Overview =====
* **BFF = Consumer**
* **Auth Service = Provider**
* Test verifies:
* request body
* response structure
* role array
* token fields
POST /auth/login - Request
json
{
"username": "john",
"password": "secret"
}
RESPONSE
json
{
"accessToken": "jwt-string",
"refreshToken": "jwt-refresh",
"expiresIn": 900,
"user": {
"id": "u123",
"email": "john@example.com",
"displayName": "John Smith",
"roles": ["ORDER.CREATE", "ORDER.VIEW"]
}
}
Recommended Test Directory Structure
/tests
┣ unit
┃ ┣ api
┃ ┣ domain
┃ ┗ infrastructure
┣ integration
┃ ┣ api
┃ ┗ data
┗ pact
┣ consumers
┃ ┗ auth
┃ ┗ login.pact.test.ts
┣ providers
┃ ┗ auth
┃ ┗ verify-login.pact.test.ts
┗ helpers
┗ pact-setup.ts
**Clean separation**
^Folder^Purpose|
|''unit/'' |Pure logic tests|
|''integration/'' |DB / Redis / route tests|
|''pact/'' |Contract testing only|
|''pact/consumers/'' |Tests written in BFF repo|
|''pact/providers/'' |Optional — verification tests|
|''pact/helpers/'' |Shared setup utilities|
Login Pact test lives in:
/tests/pact/consumers/auth/login.pact.test.ts
**Helper Setup File**
pact/helpers/pact-setup.ts
Create pact
ts
import path from "path";
import { PactV3 } from "@pact-foundation/pact";
export function createPact(providerName: string) {
return new PactV3({
consumer: "BFF-Service",
provider: providerName,
dir: path.resolve(process.cwd(), "pacts"),
logLevel: "INFO"
});
}
**login.pact.test.ts** ts
import { createPact } from "../../helpers/pact-setup";
import { MatchersV3 } from "@pact-foundation/pact";
import axios from "axios";
const { like, eachLike } = MatchersV3;
describe("Login Contract", () => {
const provider = createPact("Auth-Service");
it("logs in successfully", async () => {
provider
.given("A valid user exists")
.uponReceiving("Login request")
.withRequest({
method: "POST",
path: "/auth/login",
body: { username: "john", password: "secret" }
})
.willRespondWith({
status: 200,
body: {
accessToken: like("token"),
refreshToken: like("refresh"),
user: {
id: like("u123"),
roles: eachLike("ORDER.CREATE")
}
}
});
await provider.executeTest(async mockServer => {
const res = await axios.post(
`${mockServer.url}/auth/login`,
{ username: "john", password: "secret" }
);
expect(res.status).toBe(200);
});
});
});
====== Generated Pact Files ======
Pacts output to:
/pacts
┗ BFF-Service-Auth-Service.json