reactjsnext.jsjestjsswrmsw

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


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


Solution

  • 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.