Hi. For above. This is the client that I am using ...
# pact-js
t
Hi. For above. This is the client that I am using ...
interface MetersResponse {
errors: any[]
meters: any[]
}
const callEcoes = async (url: string, authToken: string, meters: string): Promise<MetersResponse> => {
`const response = await fetch(
${url}/api/v1/meters
, {`
method: 'POST',
headers: {
Authorization: authToken,
'Content-Type': 'application/json'
},
body: JSON.stringify({
meters: meters
})
})
return (await response.json() as MetersResponse)
}
export { callEcoes, MetersResponse }
This is my mock provider code within consumer spec ..
return mockProvider.executeTest(async (mockserver) => {
// Act
const metersResponse: MetersResponse = await callMeters(mockserver.url,'sgegegeg','2100040885876');
console.log('Type of meters response ' + typeof(metersResponse.meters[0]))
console.log('metersResponse is ' + metersResponse.meters[0]);
// Assert - did we get the expected response
expect(metersResponse.meters[0].meter).toEqual("2100040885876"); //expect(product).toStrictEqual(JSON.stringify(expectedProduct));
return;
When this runs I get the error on the console log of TypeError: Cannot read properties of undefined (reading '0'). If I just remove the .meters[0] then the whole response gets printed to the console but its inside square brackets. Can someone tell me why this response is coming back inside square brackets as this seems to be why I can't validate my assertion on the response. Thanks.
m
When you say “square brackets”, do you mean array?
We’d need to see the test definition, remember Pact is just going to send back the body you asked it to
also, you can improve the formatting using triple backticks ``` (or using the “code block” formatting item)
t
Thanks Matt. Here is my entire consumer pact spec (although I cut down the expected response for brevity. And yes its returned inside an array.
Copy code
import { PactV3 } from "@pact-foundation/pact";
import { MatchersV3 } from "@pact-foundation/pact";
import { callMeters, MetersResponse } from '../../../lambda/helpers/call-meters';
import axios, {AxiosResponse} from 'axios';
import { MetersResonse } from "../models/MetersResponse";

const { like, eachLike } = MatchersV3;
const Pact = PactV3;

const mockProvider = new Pact({
    consumer: "cs-consumer",
    provider: "db-provider",
  });

  describe("API Pact test", () => {
    it("meter exists", async () => {
      const expectedMetersResponse = {
        "errors": [],
        "meters": [
            {
                "meter": "2100040885876",
                "topline": {
                    "llf": "N13",
                    "mtc": "801",
                    "profile": "03"
            ...
           }
}

    const EXPECTED_BODY = MatchersV3.eachLike(expectedMetersResponse);

    type metersRequestBody_T = {
        meters: string;
    }

    const reqBodyExample: metersRequestBody_T = {
        meters: "2100040885876"
    }

      mockProvider
        .given("a meter with meter core 2100040885876 exists")
        .uponReceiving("a request to get meter details with a valid meter")
        .withRequest({
          method: "POST",
          path: "/api/v1/meters",
          headers: {
            'Content-Type': 'application/json'
          },
          body: like(reqBodyExample),
        })
        .willRespondWith({
          status: 200,
          headers: {
            "Content-Type": "application/json; charset=utf-8",
          },
          body: like(EXPECTED_BODY),
        });
      return mockProvider.executeTest(async (mockserver) => {
        // Act
        const metersResponse =  await callMeters(mockserver.url,'sgegegeg','2100040885876');
        console.log('metersResponse is ' + metersResponse.meters[0]);

        // Assert - did we get the expected response
        expect(metersResponse.meters[0].meter).toEqual("2100040885876");
        return;
      });
    })
  });
``````
m
Thanks!
Copy code
const EXPECTED_BODY = MatchersV3.eachLike(expectedMetersResponse);
This says “I expect an array that has items each of which has the shape `expectedMetersResponse`”
That’s why it’s an array
If you just want to match on the type, and cascade that, just use
like
t
Great! Thanks a lot. Matching correctly now and tests passing.
🎉 1