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

Error: Error: connect ECONNREFUSED 127.0.0.1:80 #494

Closed
karuppiah7890 opened this issue Dec 7, 2020 · 24 comments
Closed

Error: Error: connect ECONNREFUSED 127.0.0.1:80 #494

karuppiah7890 opened this issue Dec 7, 2020 · 24 comments
Labels
bug Something isn't working scope:node Related to MSW running in Node

Comments

@karuppiah7890
Copy link

Environment

Name Version
msw 0.21.3
node 12.19.0
OS MacOS

Request handlers

import { rest } from "msw";
import check1result from "./check1result";
import check2result from "./check2result";

function check1(queryParams: URLSearchParams): boolean {
  return true;
}

function check2(queryParams: URLSearchParams): boolean {
  return true;
}

const requestHandler = [
  rest.get("/api/resources", (req, res, ctx) => {
    let json;
    const queryParams = req.url.searchParams;

    if (check1(queryParams)) {
      json = ctx.json(check1result);
    } else if (check2(queryParams)) {
      json = ctx.json(check2result);
    }
    {
      json = ctx.json([]);
    }

    return res(ctx.delay(0), ctx.status(200), json);
  }),
];

const orderReturnMockServer = setupServer(...requestHandler);

// mws api server mock initialization
beforeAll(() =>
  orderReturnMockServer.listen({
    onUnhandledRequest: "error",
  })
);
afterAll(() => orderReturnMockServer.close());

describe('describe', () => {
    test('test1', () => {
        networkCall()
    })
    test('test2', () => {
        networkCall()
    })
})

Actual request

// Example of making a request. Provide your code here.
fetch('???').then((res) => res.json())

Current behavior

A lot of Error: Error: connect ECONNREFUSED 127.0.0.1:80 in the console logs when running my tests. But the tests
pass most of the time. Sometimes there's failures - for example timeouts. Not sure if it's related to this though, just
saying.

Expected behavior

No errors about connection refused in the console logs - as it looks like something's wrong, but I don't know what's wrong
and the tests pass too. :/

Screenshots

I'll paste some logs instead

console.error node_modules/@testing-library/react/dist/act-compat.js:52
      Error: Error: connect ECONNREFUSED 127.0.0.1:80
          at Object.dispatchError (/Users/karuppiahn/projects/deda-group/S-OMS/s-oms-ui/node_modules/jsdom/lib/jsdom/living/xhr/xhr-utils.js:62:19)
          at Request.<anonymous> (/Users/karuppiahn/projects/deda-group/S-OMS/s-oms-ui/node_modules/jsdom/lib/jsdom/living/xhr/XMLHttpRequest-impl.js:654:18)
          at Request.emit (events.js:326:22)
          at Request.onRequestError (/Users/karuppiahn/projects/deda-group/S-OMS/s-oms-ui/node_modules/request/request.js:877:8)
          at ClientRequestOverride.emit (events.js:314:20)
          at ClientRequest.<anonymous> (/Users/karuppiahn/projects/deda-group/S-OMS/s-oms-ui/node_modules/node-request-interceptor/src/interceptors/ClientRequest/ClientRequestOverride.ts:292:14)
          at ClientRequest.emit (events.js:314:20)
          at Socket.socketErrorListener (_http_client.js:428:9)
          at Socket.emit (events.js:314:20)
          at emitErrorNT (internal/streams/destroy.js:92:8) undefined


console.error node_modules/jsdom/lib/jsdom/virtual-console.js:29
      Error: Error: connect ECONNREFUSED 127.0.0.1:80
          at Object.dispatchError (/Users/karuppiahn/projects/deda-group/S-OMS/s-oms-ui/node_modules/jsdom/lib/jsdom/living/xhr/xhr-utils.js:62:19)
          at Request.<anonymous> (/Users/karuppiahn/projects/deda-group/S-OMS/s-oms-ui/node_modules/jsdom/lib/jsdom/living/xhr/XMLHttpRequest-impl.js:654:18)
          at Request.emit (events.js:326:22)
          at Request.onRequestError (/Users/karuppiahn/projects/deda-group/S-OMS/s-oms-ui/node_modules/request/request.js:877:8)
          at ClientRequestOverride.emit (events.js:314:20)
          at ClientRequest.<anonymous> (/Users/karuppiahn/projects/deda-group/S-OMS/s-oms-ui/node_modules/node-request-interceptor/src/interceptors/ClientRequest/ClientRequestOverride.ts:292:14)
          at ClientRequest.emit (events.js:314:20)
          at Socket.socketErrorListener (_http_client.js:428:9)
          at Socket.emit (events.js:314:20)
          at emitErrorNT (internal/streams/destroy.js:92:8) undefined


console.error node_modules/jsdom/lib/jsdom/virtual-console.js:29
      Error: Error: connect ECONNREFUSED 127.0.0.1:80
          at Object.dispatchError (/Users/karuppiahn/projects/deda-group/S-OMS/s-oms-ui/node_modules/jsdom/lib/jsdom/living/xhr/xhr-utils.js:62:19)
          at Request.<anonymous> (/Users/karuppiahn/projects/deda-group/S-OMS/s-oms-ui/node_modules/jsdom/lib/jsdom/living/xhr/XMLHttpRequest-impl.js:654:18)
          at Request.emit (events.js:326:22)
          at Request.onRequestError (/Users/karuppiahn/projects/deda-group/S-OMS/s-oms-ui/node_modules/request/request.js:877:8)
          at ClientRequestOverride.emit (events.js:314:20)
          at ClientRequest.<anonymous> (/Users/karuppiahn/projects/deda-group/S-OMS/s-oms-ui/node_modules/node-request-interceptor/src/interceptors/ClientRequest/ClientRequestOverride.ts:292:14)
          at ClientRequest.emit (events.js:314:20)
          at Socket.socketErrorListener (_http_client.js:428:9)
          at Socket.emit (events.js:314:20)
          at emitErrorNT (internal/streams/destroy.js:92:8) undefined

Something to add is, we do have some tests that get rid of components abruptly when they are in the middle of a fetch call (my assumption), which leads to a lot of the below logs

console.error node_modules/@testing-library/react/dist/act-compat.js:52
      Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
          in Orders (at Orders.test.tsx:121)
          in ThemeProvider (at Orders.test.tsx:120)
          in IntlProvider (at Orders.test.tsx:119)
          in Router (at Orders.test.tsx:118)
          in KeycloakProvider (at keycloak_mock_provider.tsx:46)
          in MockedKeycloakProvider (at Orders.test.tsx:117)
@karuppiah7890 karuppiah7890 added bug Something isn't working scope:node Related to MSW running in Node labels Dec 7, 2020
@tigerabrodi
Copy link
Contributor

@karuppiah7890 In your situation, I would have updated MSW as well as node, could you try that 👍?

Also, this does not seem to be related to MSW, or at least from the screenshots, if I am not mistaken 🤔

@karuppiah7890
Copy link
Author

karuppiah7890 commented Dec 7, 2020

Ah okay. It's weird yarn upgrade didn't upgrade it. I thought that would have done it.

And the logs mention about a connection and about node request interceptor. But yeah, I'll dig in and get back

@timdeschryver
Copy link
Member

@karuppiah7890 it would be great if you can share a reproduction.
Because to me, it seems like everything in the shared snippet is setup correctly.

@karuppiah7890
Copy link
Author

Makes sense. I'll try to do that too with a demo setup 👍

@marcosvega91
Copy link
Member

Just a question, do you have a single instance of setupServer? or you have more test modules with different servers?

@karuppiah7890
Copy link
Author

@marcosvega91 Ah yes. We have multiple instances 🙈

@karuppiah7890
Copy link
Author

karuppiah7890 commented Dec 8, 2020

I was thinking a bit about that too - how jest runs tests in parallel (across test files) with server running like that (same port and all). I need to dig a bit more and understand things 😅

EDIT: I forgot that it's still an interception and no actual server is running. 🙈 So, I guess running multiple "servers" is not a problem (no port conflicting issues etc)

@karuppiah7890
Copy link
Author

I was also thinking about merging all the related servers with just one server implementation - since almost all of them work in the same way with same data. It's just that I need to see how to do it. The current idea is to at least reuse the request handler (merge all request handler code, remove duplicates) and run server with that in the beforeAll setup

@karuppiah7890
Copy link
Author

UPDATE: I upgraded the version, but I still saw the connection refused errors in the logs

@marcosvega91
Copy link
Member

I asked you that because we have an issue with this approach. #474

Monkey patched modules are shared between tests, so if one test close the server instance it could be possible that another running test will have the problem that you've described. Sorry for that 😔

@karuppiah7890
Copy link
Author

karuppiah7890 commented Dec 8, 2020

Thanks for the explanation @marcosvega91 ! And I think I understand why the current features are not supporting this, so need to be sorry :) I remember reading how it's good to have one implementation (the happy path) of the server and to run the server in the Jest Test setup, before any of the tests run and to have any specific changes needed for any tests (like bad request, error cases etc) in the particular tests using the programmatic API. I'll try to see if we can do that, and I'll also have an eye on #474 . Should I close this issue then? Assuming that this is just a duplicate or a side effect of what #474 describes?

@marcosvega91
Copy link
Member

Yes we can close this and use the other issue. Thanks and sorry for your trouble 😞

@karuppiah7890
Copy link
Author

No worries!

@slim-hmidi
Copy link

I updated the node to v14.15.4 and msw to 0.25.0.
setupTests.ts:

import '@testing-library/jest-dom/extend-expect';
import {server} from './test/serverTest';

beforeAll(() => {
  server.listen();
});

afterEach(() => server.resetHandlers());

afterAll(() => server.close());

handlers.ts:

import {rest} from 'msw';
import {API} from 'constants/environment';
import urls from 'constants/urls.json';

export const modelHandlers = [
  rest.get(
    `${API}${urls.ap.checkCode}`,
    (req, res, ctx) => {
      const {code, version} = req.params;
      const mockData = {
        code: 'Code 123',
        version: 'V_1.0.0',
      };
      const isUnique = mockData.code !== code && mockData.version !== version;
      return res(ctx.json(isUnique));
    },
  ),
];

serverTests.ts:

import {setupServer} from 'msw/node';
import {rest} from 'msw';
import {modelHandlers} from './handlers';
const server = setupServer(...modelHandlers);
export {server, rest};

I got this error:

console.error
    Error: Error: connect ECONNREFUSED 127.0.0.1:8080
        at Object.dispatchError (C:\Users\xxx\Desktop\project\node_modules\jsdom\lib\jsdom\living\xhr\xhr-utils.js:62:19)
        at EventEmitter.<anonymous> (C:\Users\xxx\Desktop\project\node_modules\jsdom\lib\jsdom\living\xhr\XMLHttpRequest-impl.js:654:18)
        at EventEmitter.emit (events.js:327:22)
        at Request.<anonymous> (C:\Users\xxx\Desktop\project\node_modules\jsdom\lib\jsdom\living\xhr\xhr-utils.js:390:47)
        at Request.emit (events.js:315:20)
        at Request.onRequestError (C:\Users\xxx\Desktop\project\node_modules\request\request.js:877:8)
        at ClientRequestOverride.emit (events.js:315:20)
        at ClientRequest.<anonymous> (C:\Users\xxx\Desktop\project\node_modules\node-request-interceptor\src\interceptors\ClientRequest\ClientRequestOverride.ts:315:14)
        at ClientRequest.emit (events.js:315:20)
        at Socket.socketErrorListener (_http_client.js:469:9) undefined
        

I log the url called while testing and it's http://localhost:8080/v1/ap/checkCode?code=Code123&version=V_1.0.0.
I don't know if there is something wrong done in the configuration or it's due to jest while running the tests in parallel.
@marcosvega91 any suggestions to fix that?

@marcosvega91
Copy link
Member

marcosvega91 commented Jan 19, 2021

Hi @slim-hmidi your configuration seams right :) , Could I ask you to replace

beforeAll(() => {
  server.listen();
});

with

beforeAll(() => {
  server.listen({
    onUnhandledRequest: 'warn',
  })
});

and check then your console? Thanks, let me know

@slim-hmidi
Copy link

@marcosvega91 I got the warning concerning the handlers for the api that are not implemented like:

console.warn
    [MSW] Warning: captured a GET http://localhost:8080/v1/reference/process/type request without a corresponding request handler.
    
      If you wish to intercept this request, consider creating a request handler for it:
    
      rest.get('http://localhost:8080/v1/reference/process/type', (req, res, ctx) => {
        return res(ctx.text('body'))
      })

      at onUnhandledRequest (node_modules/msw/node/index.js:4050:21)
      at Object.<anonymous> (node_modules/msw/node/index.js:4145:25)
      at fulfilled (node_modules/msw/node/index.js:37:58)
      ```
    Should I implement handlers to different apis and does the error due to that?

@marcosvega91
Copy link
Member

marcosvega91 commented Jan 19, 2021

The api that you are handled on your code is the one that has warned ?

If not your are calling APIs in your code that are not handled by MSW. If you have missed them you can add as you have done for the other api.

@slim-hmidi
Copy link

the api I handled does not been warned

@marcosvega91
Copy link
Member

So the problem is that you have added only one handler while in your application you are making this requests.

@slim-hmidi
Copy link

you are right. I added the different handlers mentioned by the warn and it works well now. thanks a lot for your time and your help.

@marcosvega91
Copy link
Member

You're welcome :). If you need further help we are happy to help :)

@exaucae
Copy link

exaucae commented Mar 23, 2021

Hello there,

I am facing the exact same error as @karuppiah7890 with whom I share the same msw config.

I have an axios service that doesn't get mocked properly. Thanks to @marcosvega91 's tip, I found that URLs were not resolved well.

The base url in my axios.create is not taken into account, that's why I end up with the error aforementionnend.

Here is the full warning

console.warn
    [MSW] Warning: captured a request without a matching request handler:
    
      • GET http://localhost/undefined
    
    If you still wish to intercept this unhandled request, please create a request handler for it.
    Read more: https://mswjs.io/docs/getting-started/mocks

Followed by this error

 console.error
    Error: Error: connect ECONNREFUSED 127.0.0.1:80
        at Object.dispatchError (web-client\node_modules\jsdom\lib\jsdom\living\xhr\xhr-utils.js:62:19)
        at Request.<anonymous> (web-client\node_modules\jsdom\lib\jsdom\living\xhr\XMLHttpRequest-impl.js:655:18)
        at Request.emit (events.js:326:22)
        at Request.EventEmitter.emit (domain.js:486:12)
        at Request.onRequestError (web-client\node_modules\request\request.js:877:8)
        at

EDIT 1: Here are the related functions,

// service

const postman = axios.create({
  baseURL: X_SERVICE_BASE_URL,
});

export function getX(): Promise<X[] | undefined> {
  return postman.get(GET_X_ENDPOINT)
    .then((res: AxiosResponse<any[]>) => {
        return res.data.map(
          x=> doY(x),
        );
      },
    );
// test

    test.only('should get a all X', async () => {
        const result = await api.getX();
        expect(result).toHaveLength(9);
      },
    );
// handlers

export const handlers = [
  rest.post(X_SERVICE_BASE_URL + CREATE_X_ENDPOINT, (req: RestRequest<any, any>, res: ResponseComposition, ctx: RestContext) => {
      return res(
        ctx.status(201),
        ctx.json(fakeData),
      );
    },
  ),

I am using

  • react@17.0.1
  • msw@0.27.1
  • axios@0.21.1

@kettanaito
Copy link
Member

The base url in my axios.create is not taken into account, that's why I end up with the error aforementionnend.

You need to make it being taken into account manually. The URL you provide to the handler contains variables that resolve to undefined when your tests/site runs:

rest.postX_SERVICE_BASE_URL + CREATE_X_ENDPOINT

Log out those variables and track why they are undefined. Perhaps you are not loading the environmental variables when running tests? Not a library issue.

@exaucae
Copy link

exaucae commented Mar 23, 2021

You're right @kettanaito !

added setupFiles: ['dotenv/config'], in jest.config.ts and I was good to go.

Thanks!

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
bug Something isn't working scope:node Related to MSW running in Node
Projects
None yet
Development

No branches or pull requests

7 participants