Skip to main content

example-hello-world

This is a very basic Pact example, demonstrating the simplest use of a Pact Consumer

Mock provider setup

To create a Pact, we first need to define a relationship between Consumer and Provider.

This gives a mock Provider, which our Consumer can interact with.

// Configure our Pact mock Provider
const mockProvider = new Pact({
consumer: "BearServiceClient",
provider: "BearService",
cors: true,
dir: "./output/pacts",
});

Pact creation

Each Pact is declared in a "given, when, then" style.

Following the "arrange, act, assert" pattern, we:

  • arrange the expected interactions
  • act on the consumer to perform the interaction
  • assert that the mock provider received the specific interaction
// Arrange: declare our expected interactions
const expectedResponse = {
name: "Polar",
colour: "White",
};

await mockProvider.addInteraction({
state: "There are some bears",
uponReceiving: "A request for the Bear species with id 1",
willRespondWith: {
status: 200,
body: expectedResponse,
},
withRequest: {
method: "GET",
path: "/species/1",
},
});

// Act: make the Consumer interact with the mock Provider
const api = new BearConsumer(mockProvider.mockService.baseUrl);
const bear = await api.getSpecies(1);

// Assert: check the result is as expected
expect(bear).to.deep.equal(new BearSpecies("Polar", "White"));

Something else

Some other code snippets would go here when we have some

TODO: No code snippets available for this section

Pacts

{
"consumer": {
"name": "BearServiceClient"
},
"provider": {
"name": "BearService"
},
"interactions": [
{
"description": "A request for the Bear species with id 1",
"providerState": "There are some bears",
"request": {
"method": "GET",
"path": "/species/1"
},
"response": {
"status": 200,
"headers": {},
"body": {
"name": "Polar",
"colour": "White"
}
}
}
],
"metadata": {
"pactSpecification": {
"version": "2.0.0"
}
}
}