Hi, I am trying to write a consumer test for my mi...
# pact-js
s
Hi, I am trying to write a consumer test for my microservice. I am trying to generate contract to two APIs ie. create Profile (POST) and get Profile (GET). My Post interaction is always successful but GET API interaction always fails. I am not very sure what i am doing wrong. Need some guidance from the community member.
Copy code
const path = require('path');
const { PactV3, SpecificationVersion } = require('@pact-foundation/pact');
const { like, regex } = require('@pact-foundation/pact').Matchers;
const axios = require('axios');
const create_person = require('../data/create_person.json');
const create_person_response = require('../data/create_person_resonse.json');
const get_person_by_id_response = require('../data/get_person_by_id_response.json');
const PORT = 8090;
axios.defaults.timeout = 60000;
const provider = new PactV3({
    consumer: 'ProfileConsumer2',
    provider: 'ProfileProvider1',
    port: PORT,
    spec: SpecificationVersion.SPECIFICATION_VERSION_V2,
    log: path.resolve(process.cwd(), 'logs', 'pact.log'),
    dir: path.resolve(process.cwd(), 'pacts'),
    logLevel: 'debug',

});


function createProfile() {
    return <http://axios.post|axios.post>(`<http://localhost>:${PORT}/v2/profile/person/`, create_person, {
        headers: { 'Content-Type': 'application/json' },
    });
}

function findProfile() {
    return axios.get(`<http://localhost>:${PORT}/v2/profile/find`, {
        params: {
            ids: '10000017',
            scope: 'full',
        },
        headers: { 'Content-Type': 'application/json' },
    });
}

describe('Contract test for Profile', () => {
    describe('Pact with Profile API', () => {
        it('should create contract for POST API', async () => {
            await provider.addInteraction({
                state: 'Create Profile test',
                uponReceiving: 'a request to create a profile',
                withRequest: {
                    method: 'POST',
                    path: '/v2/profile/person/',
                    headers: { 'Content-Type': 'application/json' },
                    body: create_person,
                },
                willRespondWith: {
                    status: 201,
                    headers: { 'Content-Type': 'application/json' },
                    body: create_person_response,
                },
            });

            await provider.executeTest(() => {
                return createProfile().then((result) => {
                    expect(result.status).toBe(201);
                    expect(result.data).toEqual(create_person_response);
                });
            });
        });
    });

    describe('Pact test for GET API', () => {
        it('should get a profile successfully', async () => {
            await provider.addInteraction({
                state: 'should get a profile successfully',
                uponReceiving: 'A GET Request',
                withRequest: {
                    method: 'GET',
                    path: '/v2/profile/find',
                    headers: { 'Content-Type': 'application/json' },
                    query: {
                        ids: '10000017',
                        scope: 'full',
                    },
                },
                willRespondWith: {
                    status: 200,
                    headers: { 'Content-Type': 'application/json' },
                    body: get_person_by_id_response,
                },
            });

            await provider.executeTest(() => {
                return findProfile().then((result) => {
                    expect(result.status).toBe(200);
                    expect(result.data).toEqual(get_person_by_id_response);
                });
            });
        });
    });
});
I get below error when i run it
Copy code
: pact@13.1.0: Test failed for the following reasons:

  Mock server failed with the following mismatches:

        0) The following request was expected but not received: 
            Method: GET
            Path: /v2/profile/find
            Query String: ids=10000017&scope=full
 FAIL  consumer/profile.poc.test.js
  Contract test for Profile
    Pact with Profile API
      ✓ should create contract for POST API (63 ms)
    Pact test for GET API
      ✕ should get a profile successfully (64 ms)

  ● Contract test for Profile › Pact test for GET API › should get a profile successfully

    read ECONNRESET

      at Function.Object.<anonymous>.AxiosError.from (node_modules/axios/lib/core/AxiosError.js:89:14)
      at RedirectableRequest.handleRequestError (node_modules/axios/lib/adapters/http.js:610:25)
      at ClientRequest.eventHandlers.<computed> (node_modules/follow-redirects/index.js:38:24)
      at Axios.request (node_modules/axios/lib/core/Axios.js:45:41)

    Cause:
    read ECONNRESET
👋 1
m
If you only run the GET, does that work?
I’m wondering if it’s the mock server spinning up and shutting down between tests, but axios keeping the connection alive
s
Let me try with GET Call only
m
I’m wondering if maybe the advice here might help: https://github.com/pact-foundation/pact-js/issues/1066#issuecomment-1453007940
s
Only GET call works.
👍 1
m
That lends credence to the above theory. The HTTP client is holding onto a connection that is terminated between tests (the mock server will shutdown between tests)
If you can, avoid hard coding the port and use the dynamic port given to you by the test - that should prevent this issue in the first place
s
Thanks for the help. I added keep alive =false in the axios request.Also will use dynamic port as best practice.
m
no probs
you shouldn’t need to add the keep alive if you go the dynamic port option though
1