Created
January 20, 2022 17:18
-
-
Save kwiest/6b71004d99744eef891c12d2dccd9203 to your computer and use it in GitHub Desktop.
Example consumer contract test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" }); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.