Msw: connect ECONNREFUSED when i use msw with react-testing-library

Created on 24 Sep 2020  路  3Comments  路  Source: mswjs/msw

Environment

| Name | Version |
| ---- | ------- |
| msw | ^0.21.2 |
| node | v12.18.3 |
| OS | W10 |

Request handlers

const server = setupServer(
  rest.post("http://localhost:3100/users", (req, res, ctx) => {
    return res(
      ctx.json({ message: 'Usu谩rio registrado com sucesso!' }),
      ctx.status(200)
    );
  })
);
beforeAll(() => server.listen())
afterEach(() => server.resetHandlers())
afterAll(() => server.close())

My test call one function that make a http request:

test("should register user successfully when all fields is correctly filled", async () => {
   `fireEvent.click(registerButton);`
})

That calls:

const registerUser = async (
  user: IRegisterUser
): Promise<AxiosResponse<IRequestResponse>> => {
const api = axios.create({
  baseURL: "http://localhost:3100",
});
  return await api.post("/users", user);
};

I'm receiving this error:

Error: Error: connect ECONNREFUSED 127.0.0.1:3100

rest bug reproduction node

Most helpful comment

Hi @veronesecoms thanks for raising this 馃槃

Have you tried to use onUnhandledRequest option to understand if you have configured your handler well?

You can add the option in this way

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

If this is not useful for your case, could I ask you to create a reproduction repo ? I can help you better.

Thank you so much

All 3 comments

Hi @veronesecoms thanks for raising this 馃槃

Have you tried to use onUnhandledRequest option to understand if you have configured your handler well?

You can add the option in this way

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

If this is not useful for your case, could I ask you to create a reproduction repo ? I can help you better.

Thank you so much

Hey. There isn't anything evidently wrong in the code you've shared, it should work fine. I recommend looking into these points:

  • Are you using any Axios adapter?
  • What changes if you configure onUnhandledRequest per @marcosvega91's suggestion?
  • Double check that you import setupServer from msw/node and rest from msw (note no /node here).

Let us know the result of applying these suggestions. Thanks.

I'm closing this due to inactivity.

If you're still experiencing this, check the suggestions above. The ECONNREFUSED error means that your request handlers did not cover a performed request (it wasn't mocked), so it got performed as-is. Since the endpoint you were requesting didn't exist, you got the connection refusal error.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

luistak picture luistak  路  3Comments

derekr picture derekr  路  3Comments

dashed picture dashed  路  3Comments

lukesmurray picture lukesmurray  路  3Comments

hauptrolle picture hauptrolle  路  4Comments