create-react-app icon indicating copy to clipboard operation
create-react-app copied to clipboard

Jest can't find AbortController in node v16.13.0 when "testEnvironment": "node" is set in package.json

Open voinik opened this issue 4 years ago • 4 comments

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

  1. Setup a fresh CRA project
  2. Delete App.test.js
  3. 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');
    })
});
  1. Replace the default test command with: "test": "jest", in your package.json
  2. Add
"jest": {
    "testEnvironment": "node"
  },

To your package.json

  1. Run npm test

I get the following output from that. ReferenceError

voinik avatar Nov 05 '21 20:11 voinik

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

jeppester avatar Nov 16 '21 13:11 jeppester

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.

stale[bot] avatar Jan 09 '22 04:01 stale[bot]

thank you @jeppester

jaw187 avatar Mar 31 '22 12:03 jaw187

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",
};

benjie avatar Oct 30 '23 16:10 benjie