‘ReferenceError: Response is not defined’ in Jest with Node 20 when using msw

I’m using msw package to mock server response on Jest tests. I have a setupTests.js file which calls the tests/mocks/server.js file, which in turn calls the tests/mocks/handlers.js file. When I run my tests I get the error:

ReferenceError: Response is not defined

I tried setting

const fetch = global.fetch
Object.assign(global, {fetch});

in setupTests.js and in jest.polyfill,js. Also tried setting it in jest.config.json.

Nothing works. Keep getting the same error. Please help.

I’m using "msw": "^2.3.5", "jest": "^29.7.0" and node 20.14.0.

setupTests.js:

import { TextDecoder, TextEncoder } from "util";

import { server } from "./tests/mocks/server";

Object.assign(global, { TextDecoder, TextEncoder });

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

// Mocking the canvas
global.HTMLCanvasElement.prototype.getContext = jest.fn(() => ({
  fillRect: jest.fn(),
}));

global.ResizeObserver = jest.fn().mockImplementation(() => ({
  observe: jest.fn(),
  unobserve: jest.fn(),
  disconnect: jest.fn(),
}));

server.js:

import { setupServer } from "msw/node";

import { handlers } from "./handlers";

export const server = setupServer(...handlers);

handlers.js:

import { http, HttpResponse } from "msw";

export const handlers = [
  http.post(
    "https://a-website.com/",
    async (request) => {
      const { user_action } = await request.json();
      if (some_status === "something") {
        return HttpResponse.json({
          random_array: [
            {
              some_key: "some_value",
            },
          ],
        });
.
.
.
.
.