1

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

Charitha Goonewardena
  • 4,418
  • 2
  • 36
  • 38
  • 1
    Why are you rendering your component in the describe block? It needs to be in the test itself – Chase Aug 27 '22 at 19:04
  • 2
    Describe blocks are executed before beforeAll() so your server is not even available – Chase Aug 27 '22 at 19:12
  • 1
    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. – Torrents Mar 28 '23 at 23:56

1 Answers1

3

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.

Chase
  • 2,206
  • 1
  • 13
  • 17