ReferenceError: Response is not defined with msw/node + Vitest

2.4k views Asked by At

Was wondering if anyone has encountered the following issue with the latest msw (2.0.9) and trying to run it with the latest Vite (5.0.2) + Vitest (0.34.6)? No matter what I do, I cannot get past this error of Response somehow being undefined despite having cross-fetch installed as well along with @types/node.

My installed TypeScript version is 5.3.2 which doesn't satisfy the peerDependency of msw which is set up to 5.2.x, but I did downgrade it to meet the requirements and I was still met with the same error.

ReferenceError: Response is not defined
 ❯ node_modules/.pnpm/[email protected][email protected]/node_modules/msw/lib/core/HttpResponse.mjs:5:28
 ❯ src/setupTests.ts:3:31
      1| import "@testing-library/jest-dom";
      2| import fetch from "cross-fetch";
      3| import { setupServer } from "msw/node";
       |                               ^

For reference, my vite.config.ts is the following:

import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
import { configDefaults } from "vitest/config";

export default defineConfig({
  plugins: [react()],
  server: {
    host: true,
    port: 4000,
  },
  define: {
    "process.env": {
      VERSION: process.env.VERSION,
      PLAYWRIGHT: process.env.PLAYWRIGHT,
      USE_MSW: process.env.USE_MSW,
    },
  },
  resolve: {
    mainFields: ["module"],
    alias: {
      src: "/src",
    },
  },
  test: {
    environment: "jsdom",
    globals: true,
    setupFiles: "./src/setupTests.ts",
    watch: false,
    // Need to concat with config defaults otherwise node_modules get tested
    exclude: [...configDefaults.exclude, "src/e2e/*"],
    coverage: {
      provider: "istanbul",
      exclude: [".eslintrc.cjs", "src/index.tsx", "playwright.config.ts", ".github/*"],
      all: true,
      lines: 100,
      functions: 100,
      branches: 100,
      statements: 100,
      reporter: ["json", "lcov", "text", "cobertura"],
    },
  },
});

Hoping someone can help.

2

There are 2 answers

1
danchez On BEST ANSWER

Managed to finally get through it after trying so many different things. Turns out, the only thing that needed to be done in setupTests.ts was the following:

import "cross-fetch/polyfill";

0
Maximilon Baddeley On

I am currently experiencing this issue when deploying to an aws environment that runs node 16. ( this issue was logged from building into the pipeline). I've asked middleware to update to a newer version consequently moving node versions from 16 to 18 and hopefully resolving the issue.

My local runs higher than 18 so the tests work fine there.