0

I'm trying to test my web page using MSW, jest, and react-testing-library. The app is built with NextJS and JS.

I set up the MSW browser worker and everything goes fine, but when I tried to do the same with the node server throws an error.

The error is the following:

ReferenceError: fetch is not defined

I know that fetch is a browser method and doesn't run on node. I thought that setting up MSW will, somehow, override fetch to run in node for the test.

Does anyone know how I had some bad setup or do I have to do more setting things to run my test?

Thanks in advance.

Manoj Agrawal
  • 429
  • 3
  • 10
Rommel
  • 69
  • 1
  • 5

1 Answers1

0

I finally find a solution.

May it not be the best so I am would like to know if there is a better or other solution.

What I have done is the following:

In my setupTest.js file I added fetchPolifill

import "@testing-library/jest-dom/extend-expect";

import { server } from "../mocks/server";
const fetchPolifill = require("whatwg-fetch");

global.fetch = fetchPolifill.fetch;

beforeAll(() => {
  console.log("listening...");
  server.listen();
});

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

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

to run you need to install whatwg-fetch

npm i whatwg-fetch --save-dev

Rommel
  • 69
  • 1
  • 5