Jest can't find AbortController in node v16.13.0

Viewed 1379

I am using Jest to run my tests. After an upgrade to Node v16.13.0 (the LTS version) from v12, I got the following error:

ReferenceError: AbortController is not defined

Whereas running the code manually with Node worked fine.

I upgraded all my packages to the newest versions during the upgrade to v16. I had been using a polyfill for a mock AbortController because I was using Node v12 before the upgrade. Node v16 comes with its own AbortController, so I removed the polyfill. I am using TypeScript 4.4.4, in case that's relevant (this is not a TypeScript error).

This error did not occur with the polyfill.

It seems that when Jest runs it is not using the same environment compared to when I manually run my app with Node.

I tried the following:

  • Make Node v16.13.0 the default version using nvm
  • Remove all other versions of Node installed except v16.13.0
  • Run console.log(process.env) at the start of the test and check what Node version is being used -> All references to Node had that same version: 16.13.0.

I've been at this for hours and it seems nobody on the internet has had this problem. Does anyone have any idea what is going on?

2 Answers

After more digging I 'fixed' the issue. Simply remove "testEnvironment": "node" (inside "jest": {...}) from your package.json.

I stumbled upon the option to set Jest's testing environment (https://jestjs.io/docs/configuration#testenvironment-string), and I noticed my package.json already contained that setting (under "jest": {...}) and it was set to: "testEnvironment": "node". According to the docs, however, it's the default, so I didn't think anything of it.

Hours later, in a ditch effort of desperation I decided to remove it... And voilĂ , it solved the problem.

Apparently setting the "testEnvironment" configuration to the same thing as its default changes Jest's running environment, which is very counterintuitive and confusing to me.

Edit: This is caused by Create React App. I compared an empty repo with only jest installed with a CRA repo, which comes with jest. Changing the test command to jest and adding the configuration above triggers the issue. If you use the default react-scripts test command, CRA will not run the tests and give you a big red error that they don't support the "testEnvironment" setting.

I experienced this with node v16.15.0 this when downgrading jest from v27 -> v26. Reverting back to jest v27 fixed this error.

Related