Search code examples
javascriptconsumerpactcontract

Problem: Consumer Driven Contract Testing with Pact


Im writing a small programm for a University project. I'd like to test it with the pact framewok. Unfortunately, no Pact.json file is created for me, although there are no errors. My Consumer iss written in Javascript. Below you can see the source code of my javascript file, the console output and my package.json file:

const {Pact} = require('@pact-foundation/pact');
const axios = require('axios');
const path = require('path');


describe('Pact Consumer', () => {
    const provider = new Pact({
        consumer: 'consumer',
        provider: 'producer',
        host:'127.0.0.1',
        port: 1234,
        log: path.resolve(process.cwd(), 'logs', 'pact.log'),
        dir: path.resolve(process.cwd(), 'pacts'),
        logLevel: 'INFO',
    });

    beforeAll(() => provider.setup());
    jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
    describe('consumer', () => {

        beforeEach
        (() =>

            provider.addInteraction({
                state: "valid date",
                uponReceiving: "a request for JSON data",
                withRequest: {
                    method: "GET",
                    path: "/test",
                    headers: { Accept: "application/json" },
                },
                willRespondWith: {
                    status: 200,
                    headers: { "Content-Type": "application/json" },
                    body:
                        {
                            name: 'Scherr',
                            surname: 'Valerian',
                            age: 28,
                        },

                },


            }),


        );

    });



    describe('test', () => {
        it('should return the correct data', () => {

          return  axios.get('localhost:1234/test').then(response => {
                expect(response[0].name).toBe('Scherr');
                expect(response[0].surname).toBe('Valerian');
                expect(response[0].age).toBe(28);
            }).then(()=> provider.verify())
        });
    });

    afterAll(() => {
        return provider.finalize();
    });
});


Console Output:

   Error: getaddrinfo ENOTFOUND 1234
Expected :
Actual   :
<Click to see difference>

error properties: Object({ errno: 'ENOTFOUND', code: 'ENOTFOUND', syscall: 'getaddrinfo', hostname: '1234', config: Object({ url: 'localhost:1234/test', method: 'get', headers: Object({ Accept: 'application/json, text/plain, */*', User-Agent: 'axios/0.19.2' }), transformRequest: [ Function ], transformResponse: [ Function ], timeout: 0, adapter: Function, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', maxContentLength: -1, validateStatus: Function, data: undefined }), request: Writable({ _writableState: WritableState({ objectMode: false, highWaterMark: 16384, finalCalled: false, needDrain: false, ending: false, ended: false, finished: false, destroyed: false, decodeStrings: true, defaultEncoding: 'utf8', length: 0, writing: false, corked: 0, sync: true, bufferProcessing: false, onwrite: Function, writecb: null, writelen: 0, afterWriteTickInfo: null, bufferedRequest: null, lastBufferedRequest: null, pendingcb: 0, prefinished: false, errorEmitted: false, emitClose: true, autoDestroy: false ...
Error: getaddrinfo ENOTFOUND 1234
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:64:26)

package.json:

{
  "name": "webservice",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "jasmine"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@pact-foundation/pact": "^9.11.0",
    "@pact-foundation/pact-node": "^10.9.5",
    "axios": "^0.19.2",
    "jasmine": "^3.5.0"
  },
  "devDependencies": {
    "pact": "^4.3.2"
  }
}

I am grateful for any help and thanks in advance


Solution

  • I can't tell without logs here, but one things is for sure: your call to axios.get and provider.verify are promises and are not being correctly, meaning the execution of certain things will be out of order or will not actually execute at all.

    Simply prefixing both with return should fix that issue.

    See https://github.com/pact-foundation/pact-js#test-fails-when-it-should-pass.