Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Getting error: connect ECONNREFUSED ::1:<port> using PactV3 and Jest #1398

Closed
4 tasks
pulak777 opened this issue Mar 10, 2025 · 11 comments
Closed
4 tasks

Getting error: connect ECONNREFUSED ::1:<port> using PactV3 and Jest #1398

pulak777 opened this issue Mar 10, 2025 · 11 comments
Labels
awaiting feedback Awaiting Feedback from OP bug Indicates an unexpected problem or unintended behavior triage This issue is yet to be triaged by a maintainer

Comments

@pulak777
Copy link

pulak777 commented Mar 10, 2025

Software versions

Please provide at least OS and version of pact-js

  • OS: Windows 11 Enterprise
  • Consumer Pact library: Pact JS v14.0.0
  • Node Version: v18.20.2

Issue Checklist

Please confirm the following:

  • [ *] I have upgraded to the latest
  • I have the read the FAQs in the Readme
  • I have triple checked, that there are no unhandled promises in my code and have read the section on intermittent test failures
  • I have set my log level to debug and attached a log file showing the complete request/response cycle
  • For bonus points and virtual high fives, I have created a reproduceable git repository (see below) to illustrate the problem

Expected behaviour

fill in here

Actual behaviour

    Error: Error: connect ECONNREFUSED ::1:1234
        at Object.dispatchError (C:\app\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\living\xhr\xhr-utils.js:63:19)
        at Request.<anonymous> (C:\app\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\living\xhr\XMLHttpRequest-impl.js:655:18)
        at Request.emit (node:events:529:35)
        at Request.emit (node:domain:489:12)
        at ClientRequest.<anonymous> (C:\app\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\living\helpers\http-request.js:121:14)
        at ClientRequest.emit (node:events:517:28)
        at ClientRequest.emit (node:domain:489:12)
        at Socket.socketErrorListener (node:_http_client:501:9)
        at Socket.emit (node:events:517:28)
        at Socket.emit (node:domain:489:12)
        at emitErrorNT (node:internal/streams/destroy:151:8)
        at emitErrorCloseNT (node:internal/streams/destroy:116:3)
        at processTicksAndRejections (node:internal/process/task_queues:82:21) {
      type: 'XMLHttpRequest'
    }

      at VirtualConsole.<anonymous> (node_modules/jest-environment-jsdom/build/index.js:63:23)

Steps to reproduce

How can someone else reproduce this bug?

// jest.config.pact

import { JestConfigWithTsJest } from 'ts-jest';

const esModules = [
  '.*\\.mjs$',
  'lodash-es',
  'color-alpha',
  'color-name',
  'color-parse',
].join('|');

const config: JestConfigWithTsJest = {
  roots: ['src'],
  testMatch: ['**/?(*.)+(pact).ts'],
  preset: 'jest-preset-angular',
  setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
  transformIgnorePatterns: [`node_modules/(?!${esModules})`],
  testEnvironmentOptions: {
    url: 'http://localhost:1234',
  },
  verbose: true,
  collectCoverage: false,
  moduleNameMapper: {
    '^color\\-alpha$': '<rootDir>/node_modules/color-alpha',
    '^color\\-name$': '<rootDir>/node_modules/color-name',
    '^color\\-parse$': '<rootDir>/node_modules/color-parse',
  },
};

export default config;

// setup-jest

import { setupZoneTestEnv } from 'jest-preset-angular/setup-env/zone';

setupZoneTestEnv();

// test.pact

describe('/test-api with Pact', () => {
  const provider: PactV3 = new PactV3({
    consumer: 'test-ui',
    port: 1234,
    host: 'localhost',
    provider: 'test-app',
    logLevel: 'debug',
  });

  beforeEach(async () => {
    TestBed.configureTestingModule({
      imports: [HttpClientModule],
      providers: [TestService],
      teardown: { destroyAfterEach: false },
    });
  });

  describe('test service returns', () => {
    const interaction: V3Interaction = {
      states: [{ description: 'some description' }],
      uponReceiving: 'some description',
      willRespondWith: {
        body: testlMatcher,
        status: 200,
      },
      withRequest: {
        method: 'GET',
        path: `v1/test/url`,
      },
    };

    beforeAll(() => {
      provider.addInteraction(interaction);
    });

    it('test scenario', async () => {
      const testService = TestBed.inject(
        TestService,
      );
      await testService
        .testMethod()
        .toPromise()
        .then((testResponse) => {
          expect(testResponse).toEqual(
            mockResponse,
          );
        });
    });
  });
});

Relevant log files

Please ensure you set logging to DEBUG and attach any relevant log files here (or link to a gist).

NA

@pulak777 pulak777 added bug Indicates an unexpected problem or unintended behavior triage This issue is yet to be triaged by a maintainer labels Mar 10, 2025
@YOU54F
Copy link
Member

YOU54F commented Mar 10, 2025

set the host to 127.0.0.1, it's trying to resolve to an ipv6 address

@pulak777
Copy link
Author

It worked thanks! Previously I only updated the host to 127.0.0.1 in pact constructor, need to change in both jest config and in pact constructor

@pulak777
Copy link
Author

pulak777 commented Mar 10, 2025

This fix works with Pact, but the same issue remains with PactV3

Error: connect ECONNREFUSED 127.0.0.1:1234

@mefellows
Copy link
Member

What have you passed into the PactV3 constructor? Could you please attach DEBUG logs?

@mefellows mefellows added the awaiting feedback Awaiting Feedback from OP label Mar 10, 2025
@pulak777
Copy link
Author

Hello, here's the PactV3 constructor and debug logs

new PactV3({
    consumer: 'consumer-app',
    port: 1234,
    host: '127.0.0.1',
    provider: 'provider-app',
    logLevel: 'debug',
  });
[10:36:43.106] DEBUG (27692): pact-core@16.0.0: binding path #0: : attempting to load native module from: 

 - C:\app\node_modules\@pact-foundation\pact-core-windows-x64\prebuilds\win32-x64
   source: pact-js-core binding lookup

 - You can override via PACT_PREBUILD_LOCATION

[10:36:43.113] INFO (27692): 0.4.22: pact native library successfully found, and the correct version
[10:36:43.114] DEBUG (27692): pact-core@16.0.0: Initialising native core at log level 'debug'
2025-03-11T10:36:43.116625Z DEBUG ThreadId(01) pact_ffi::mock_server::handles: Failed to parse the value, treating it as a plain string: expected value at line 1 column 1
2025-03-11T10:36:43.117079Z DEBUG ThreadId(01) pact_models::content_types: Detecting content type from contents: '{_<reducted>_}'
2025-03-11T10:36:43.121402Z DEBUG ThreadId(01) pact_ffi::mock_server::bodies: Path = $
2025-03-11T10:36:43.121589Z DEBUG ThreadId(01) pact_ffi::mock_server::bodies: detected pact:matcher:type, will configure a matcher
2025-03-11T10:36:43.121770Z DEBUG ThreadId(01) pact_ffi::mock_server::bodies: Path = $
2025-03-11T10:36:43.121872Z DEBUG ThreadId(01) pact_ffi::mock_server::bodies: Path = $[*]
2025-03-11T10:36:43.121976Z DEBUG ThreadId(01) pact_ffi::mock_server::bodies: Configuring a normal object
_<reducted>_
2025-03-11T10:36:43.134192Z DEBUG ThreadId(01) pact_ffi::mock_server::bodies: detected pact:matcher:type, will configure a matcher
  console.error
    Error: Error: connect ECONNREFUSED 127.0.0.1:1234
        at Object.dispatchError (C:\app\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\living\xhr\xhr-utils.js:63:19)
        at Request.<anonymous> (C:\app\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\living\xhr\XMLHttpRequest-impl.js:655:18)
        at Request.emit (node:events:529:35)
        at Request.emit (node:domain:489:12)
        at ClientRequest.<anonymous> (C:\app\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\living\helpers\http-request.js:121:14)
        at ClientRequest.emit (node:events:517:28)
        at ClientRequest.emit (node:domain:489:12)
        at Socket.socketErrorListener (node:_http_client:501:9)
        at Socket.emit (node:events:517:28)
        at Socket.emit (node:domain:489:12)
        at emitErrorNT (node:internal/streams/destroy:151:8)
        at emitErrorCloseNT (node:internal/streams/destroy:116:3)
        at processTicksAndRejections (node:internal/process/task_queues:82:21) {
      type: 'XMLHttpRequest'
    }

      at VirtualConsole.<anonymous> (node_modules/jest-environment-jsdom/build/index.js:63:23)

Also attaching the pact file (using pact specification v2)

{
  "consumer": {
    "name": "consumer-app"
  },
  "interactions": [
    <reducted>
  ],
  "metadata": {
    "pact-js": {
      "version": "14.0.0"
    },
    "pactRust": {
      "ffi": "0.4.22",
      "models": "1.2.3"
    },
    "pactSpecification": {
      "version": "2.0.0"
    }
  },
  "provider": {
    "name": "provider-app"
  }
}

@mefellows
Copy link
Member

You've redacted the log file, but I need to see the part where it starts the mock server - this seems to be missing.

Additionally, if you have the code that goes with your test that would be helpful. It looks like your code is trying to connect to the server too early, but that could be a red herring.

    beforeAll(() => {
      provider.addInteraction(interaction); // <- this is a promise, and it's not awaited. See the bug template for checking dangling promises
    });

@pulak777
Copy link
Author

The code is same as in the ticket description (only change is in the host value) (same error is thrown with awaited addInteraction)

For the reducted sections, I triple checked, it only contain the model specifcations.

For mock server this line might be of use -

2025-03-11T10:36:43.116625Z DEBUG ThreadId(01) pact_ffi::mock_server::handles: Failed to parse the value, treating it as a plain string: expected value at line 1 column 1

It looks like your code is trying to connect to the server too early, but that could be a red herring.

Let me try increasing the test timeout value

@pulak777
Copy link
Author

Same error despite increasing jest timeout.

Here the extended log

[11:28:18.773] DEBUG (32880): pact-core@16.0.0: binding path #0: : attempting to load native module from: 

 - C:\app\node_modules\@pact-foundation\pact-core-windows-x64\prebuilds\win32-x64
   source: pact-js-core binding lookup

 - You can override via PACT_PREBUILD_LOCATION

[11:28:18.781] INFO (32880): 0.4.22: pact native library successfully found, and the correct version
[11:28:18.782] DEBUG (32880): pact-core@16.0.0: Initialising native core at log level 'debug'
2025-03-11T11:28:18.785426Z DEBUG ThreadId(01) pact_ffi::mock_server::handles: Failed to parse the value, treating it as a plain string: expected value at line 1 column 1
2025-03-11T11:28:18.786081Z DEBUG ThreadId(01) pact_models::content_types: Detecting content type from contents: '{"min":1,"pact:matcher:type":"type","value":[{"id":{"pact:matcher:type":"type","value":"123"},"label":{"pact:matcher:type":"type","value":"label"}}]}'
2025-03-11T11:28:18.791525Z DEBUG ThreadId(01) pact_ffi::mock_server::bodies: Path = $
2025-03-11T11:28:18.791782Z DEBUG ThreadId(01) pact_ffi::mock_server::bodies: detected pact:matcher:type, will configure a matcher
2025-03-11T11:28:18.792072Z DEBUG ThreadId(01) pact_ffi::mock_server::bodies: Path = $
2025-03-11T11:28:18.792214Z DEBUG ThreadId(01) pact_ffi::mock_server::bodies: Path = $[*]
2025-03-11T11:28:18.797846Z DEBUG ThreadId(01) pact_ffi::mock_server::bodies: detected pact:matcher:type, will configure a matcher
2025-03-11T11:28:18.797974Z DEBUG ThreadId(01) pact_ffi::mock_server::bodies: detected pact:generator:type, will configure a generators
2025-03-11T11:28:18.798113Z DEBUG ThreadId(01) pact_ffi::mock_server::bodies: Path = $[*].id
2025-03-11T11:28:18.798272Z DEBUG ThreadId(01) pact_ffi::mock_server::bodies: detected pact:matcher:type, will configure a matcher
2025-03-11T11:28:18.798400Z DEBUG ThreadId(01) pact_ffi::mock_server::bodies: Path = $[*].label
2025-03-11T11:28:18.816925Z DEBUG ThreadId(01) pact_ffi::mock_server::bodies: detected pact:matcher:type, will configure a matcher
  console.error
    Error: Error: connect ECONNREFUSED 127.0.0.1:1234
        at Object.dispatchError (C:\app\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\living\xhr\xhr-utils.js:63:19)
        at Request.<anonymous> (C:\app\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\living\xhr\XMLHttpRequest-impl.js:655:18)
        at Request.emit (node:events:529:35)
        at Request.emit (node:domain:489:12)
        at ClientRequest.<anonymous> (C:\app\node_modules\jest-environment-jsdom\node_modules\jsdom\lib\jsdom\living\helpers\http-request.js:121:14)
        at ClientRequest.emit (node:events:517:28)
        at ClientRequest.emit (node:domain:489:12)
        at Socket.socketErrorListener (node:_http_client:501:9)
        at Socket.emit (node:events:517:28)
        at Socket.emit (node:domain:489:12)
        at emitErrorNT (node:internal/streams/destroy:151:8)
        at emitErrorCloseNT (node:internal/streams/destroy:116:3)
        at processTicksAndRejections (node:internal/process/task_queues:82:21) {
      type: 'XMLHttpRequest'
    }

      at VirtualConsole.<anonymous> (node_modules/jest-environment-jsdom/build/index.js:63:23)

 FAIL  src/app/services/test.service.pact.ts (5.846 s)
  /test-app with Pact
    someFunction should return the head of an agreement detail                                                                                                                                  
      × when no revision is provided (53 ms)                                                                                                                                                                       

  ● /test-app with Pact › someFunction should return the head of an agreement detail › when no revision is provided

    Http failure response for /v1/apps/data: 0 Unknown Error

@YOU54F
Copy link
Member

YOU54F commented Mar 11, 2025

any chance you could create a minimal repro on github? I can test it on a few systems

@pulak777
Copy link
Author

pulak777 commented Mar 11, 2025

Looks like the issue was caused by the mock server not being initialized inside addInteraction in PactV3 (unlike in Pact), instead here need to invoke executeTest

Below test runs without throwing the error -

 it('some test', async () => {
      await provider.executeTest(async () => {
        const testService = TestBed.inject(
          TestService,
        );
        return testService
          .testMethod()
          .toPromise()
          .then(
            (testResponse) => {
              expect(testResponse).toEqual(
                mockTestResponse
              );
            },
          );
      });
    });

It's there in the examples too https://github.com/pact-foundation/pact-js/blob/master/examples/v3/e2e/test/consumer.spec.js

@mefellows
Copy link
Member

Yeah PactV3 is a separate interface altogether. Thanks for reporting back 🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
awaiting feedback Awaiting Feedback from OP bug Indicates an unexpected problem or unintended behavior triage This issue is yet to be triaged by a maintainer
Projects
None yet
Development

No branches or pull requests

3 participants