Getting `ReferenceError: TextEncoder is not defined` after upgrading Jest

723 views Asked by At

I'm currently in the process of ejecting a rather large create-react-app project. While I was at it, I also updated Jest's version from ~27 to ~29. There was a breaking change in v28 that required me to manually install jest-environment-jsdom. After doing that, I'm getting an error in one of my tests.

ReferenceError: TextEncoder is not defined

This error comes from inside react-dom/server, which I'm importing in one of the production files.

The problem is that TextEncoder exists globally in the browser but needs to be imported from utils in Node.JS. react-dom/server has 2 different output files, one for the browser and one for Node.JS, solving this problem, if you import the correct file. Since the Jest update, this import is resolved incorrectly. Jest imports the browser file, not the node file. Before the update, Jest resolved the import correctly.

I know that doing something like

global.TextEncoder = require("utils").TextEncoder;

would work, but I was wondering if there was a less hacky solution. It seems implausible to me that that's the necessary way to go since the Jest update.

Some more info:
Jest version: 29.7.0

Since ejecting, my package.json contains this jest section:

"jest": {
    "roots": [
      "<rootDir>/src"
    ],
    "collectCoverageFrom": [
      "src/**/*.{js,jsx,ts,tsx}",
      "!src/**/*.d.ts"
    ],
    "setupFiles": [
      "react-app-polyfill/jsdom"
    ],
    "setupFilesAfterEnv": [
      "<rootDir>/src/setupTests.ts"
    ],
    "testMatch": [
      "<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
      "<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}"
    ],
    "testEnvironment": "jsdom"
    "transform": {
      "^.+\\.(js|jsx|mjs|cjs|ts|tsx)$": "<rootDir>/config/jest/babelTransform.js",
      "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
      "^(?!.*\\.(js|jsx|mjs|cjs|ts|tsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
    },
    "transformIgnorePatterns": [
      "[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs|cjs|ts|tsx)$",
      "^.+\\.module\\.(css|sass|scss)$"
    ],
    "modulePaths": [],
    "moduleNameMapper": {
      "^react-native$": "react-native-web",
      "^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy",
      "^uuid$": "<rootDir>/node_modules/uuid/dist/umd/uuid.min.js"
    },
    "moduleFileExtensions": [
      "web.js",
      "js",
      "web.ts",
      "ts",
      "web.tsx",
      "tsx",
      "json",
      "web.jsx",
      "jsx",
      "node"
    ],
    "watchPlugins": [
      "jest-watch-typeahead/filename",
      "jest-watch-typeahead/testname"
    ],
    "resetMocks": true,
    "globalSetup": "./src/global-setup.js"
  },
0

There are 0 answers