1
+ import { SpecificationVersion, PactV4, MatchersV3 } from "@pact-foundation/pact";
2
+ import { ThingAPI } from './thing'
3
+
4
+ // Extract matchers here to improve readability when used in the test
5
+ const { like } = MatchersV3;
6
+
7
+ // Create a 3 level test hierarchy
8
+ //
9
+ // 1. Top level describe block containing the name of the API being tested
10
+ // 2. Describe block for the specific API endpoint
11
+ // 3. Test block for the specific test case
12
+ // 4. Execute the test case
13
+ // 5. Call the API under test
14
+ // 6. Assert the response
15
+ // 8. Use Pact matchers to constrain and test the Provider response
16
+ // 7. Use Jest matchers to assert the API client behaviour
17
+
18
+ // Top level - name of the API
19
+ describe("Thing API", () => {
20
+ // Use the PactV4 class, and serialise the Pact as V4 Pact Specification
21
+ const pact = new PactV4({
22
+ consumer: "ThingConsumer",
23
+ provider: "ThingProvider",
24
+ spec: SpecificationVersion.SPECIFICATION_VERSION_V4,
25
+ });
26
+
27
+ // Level 2 - Describe block for the specific API endpoint
28
+ describe("GET /thing/:id", () => {
29
+
30
+ // Level 3 - Test block for the specific test case
31
+ test("given a valid thing, returns 200", async () => {
32
+ await pact
33
+ .addInteraction()
34
+ .given("a thing with id 1 exists")
35
+ .uponReceiving("a request for a valid thing")
36
+ // Avoid matchers on the request unless necessary
37
+ .withRequest("GET", "/thing/1", (builder) => {
38
+ builder.headers({ Accept: "application/json" });
39
+ })
40
+ .willRespondWith(200, (builder) => {
41
+ // Use loose matchers where possible, to avoid unnecessary constraints on the provider
42
+ builder.jsonBody(
43
+ like({
44
+ id: 1,
45
+ name: "Thing 1",
46
+ price: 100,
47
+ })
48
+ );
49
+ })
50
+ .executeTest(async (mockserver) => {
51
+ // Instantiate the ThingAPI client
52
+ const ThingAPI = new ThingAPI(mockserver.url);
53
+
54
+ // Call the API under test
55
+ const Thing = await ThingAPI.getThingById(1);
56
+
57
+ // Use Jest matchers to assert the response
58
+ expect(Thing).toEqual({
59
+ id: 1,
60
+ name: "Some 1",
61
+ price: 100,
62
+ });
63
+ });
64
+ });
65
+ });
66
+ });
0 commit comments