create-react-app
create-react-app copied to clipboard
Jest can't find AbortController in node v16.13.0 when "testEnvironment": "node" is set in package.json
Description
If you have
"jest": {
"testEnvironment": "node"
},
set in your package.json, and you run an npm command with jest in it (e.g. "test": "jest"), you'll get:
ReferenceError: AbortController is not defined
This happens despite AbortController being available in Node v16.13.0.
Running code using AbortController without Jest works fine.
It seems CRA is changing Jest's node environment somehow?
I'm aware that CRA does not allow the "testEnvironment" setting to be set in the package.json when using react-scripts test. I simply did not expect setting the "testEnvironment" setting to its default ("node") to seemingly change the environment.
Environment
CRA v4.0.3 Node v16.13.0 npm v8.1.0
Steps to reproduce
- Setup a fresh CRA project
- Delete App.test.js
- Add 2 new files to src:
// src/abortControllerCode.js
function start() {
const abortController = new AbortController();
abortController.abort();
return 'foo';
}
module.exports = { start }
and
// src/abortControllerCode.test.js
const { start } = require('./abortControllerCode');
describe('AbortController test', () => {
it('Should not throw', () => {
expect(start()).toBe('foo');
})
});
- Replace the default test command with:
"test": "jest",in your package.json - Add
"jest": {
"testEnvironment": "node"
},
To your package.json
- Run
npm test
I get the following output from that.

I had this same problem. After much troubleshooting it turned out that I used an old version of jest.
Jest started supporting AbortController with https://github.com/facebook/jest/pull/11182 which is included from version 27.0.0
This issue has been automatically marked as stale because it has not had any recent activity. It will be closed in 5 days if no further activity occurs.
thank you @jeppester
If, for reasons I won't go into, you happen to be stuck on Jest 26, a workaround for this is to create your own Jest environment:
// __tests__/nodeEnvironment.js
const NodeEnvironment = require("jest-environment-node");
class CustomEnvironment extends NodeEnvironment {
constructor(config, context) {
super(config, context);
this.global.AbortController = global.AbortController;
}
}
module.exports = CustomEnvironment;
// jest.config.js
module.exports = {
/* ... */
testEnvironment: "./__tests__/nodeEnvironment.js",
};