Skip to content

Instantly share code, notes, and snippets.

@kwiest
Created January 20, 2022 17:18
Show Gist options
  • Save kwiest/6b71004d99744eef891c12d2dccd9203 to your computer and use it in GitHub Desktop.
Save kwiest/6b71004d99744eef891c12d2dccd9203 to your computer and use it in GitHub Desktop.
Example consumer contract test
import { Pact } from "@pact-foundation/pact";
import { like } from "@pact-foundation/pact/src/dsl/matchers";
import { CartApi } from ".";
const provider = new Pact({
consumer: "MockCartConsumer",
provider: "CartService",
logLevel: "info",
});
describe("Cart Api", () => {
let api: { sayHello(): Promise<any> };
beforeAll(async () => {
await provider.setup().then((opts) => {
const baseURL = "http://" + [opts.host, opts.port].join(":");
api = CartApi(baseURL);
});
});
afterAll(() => provider.finalize());
test("GET /hello", async () => {
await provider.addInteraction({
state: "stateless",
uponReceiving: "say hello",
withRequest: {
method: "GET",
path: "/hello",
},
willRespondWith: {
status: 200,
headers: {
"Content-Type": "application/json",
},
body: like({ hello: "world" }),
},
});
await expect(api.sayHello()).resolves.toEqual({ hello: "world" });
});
});
@kwiest
Copy link
Author

kwiest commented Jan 20, 2022

The way this works is you're encouraged to write your consumer tests first.

For a consumer test, this creates a mock provider that returns stubbed responses, however once you publish the contract and attempt to verify the provider side, it makes live requests and matches them against the stubbed responses - this is kind of like a reverse order of the Ruby/Rails VCR paradigm.

@jason-bb
Copy link

This is super sane/sensible 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment