connect ECONNREFUSED when using msw with react-testing-library (NextJS + SWR)
Asked Answered
H

1

2

I'm struggling mocking the SWR fetch api call with MSW.

You can reproduce the issue with this repo: https://github.com/charitha95/msw-test

Error that I'm facing when using MSW:

Error: connect ECONNREFUSED 127.0.0.1:80 at Object.dispatchError

enter image description here

My test file:

import "@testing-library/jest-dom";
import {
  render,
  screen,
  waitForElementToBeRemoved,
} from "@testing-library/react";
import { rest } from "msw";
import { setupServer } from "msw/node";
import Home from "../pages/index";

const server = setupServer(
  rest.get("/api/colors", (req, res, ctx) => {
    return res(
      ctx.delay(100),
      ctx.json([
        {
          color: "red",
          value: "#f00",
        },
        {
          color: "green",
          value: "#0f0",
        },
      ])
    );
  })
);

beforeAll(() => server.listen());
afterAll(() => server.close());
afterEach(() => server.resetHandlers());

describe("Home", () => {
  render(<Home />);
  it("renders list of colors", async () => {
    await waitForElementToBeRemoved(screen.getByText("loading..."));

    const colors = screen.getByTestId("color-list");
    expect(colors).toBeInTheDocument();
    expect(screen.getByText("BMW")).toBeInTheDocument();
  }, 1500);
});

Things I looked at, but no luck:
github
stackoverflow

Headstrong answered 27/8, 2022 at 18:56 Comment(3)
Why are you rendering your component in the describe block? It needs to be in the test itselfOneal
Describe blocks are executed before beforeAll() so your server is not even availableOneal
Thanks for submitting an excellent question with plenty of information Charitha. We had a codebase with similar but inconsistent errors, and this was the key to helping us get it solved.Titi
O
5

Jest executes all describe handlers in a test file before it executes any of the actual tests. This is another reason to do setup and teardown inside before* and after* handlers rather than inside the describe blocks. Once the describe blocks are complete, by default Jest runs all the tests serially in the order they were encountered in the collection phase, waiting for each to finish and be tidied up before moving on.

You should not be doing any setup in describe blocks. The reason this is failing is because your server.listen hasn't even been called when you render the component.

Oneal answered 27/8, 2022 at 19:16 Comment(2)
You are right! now it works as expected my man! thank youHeadstrong
Thanks for the quote Chase. Here is where it came from: jestjs.io/docs/setup-teardown#order-of-executionTiti

© 2022 - 2024 — McMap. All rights reserved.