Jest, typeOfEnv is node, pollyfill with node-fetch, complains about require() when clearly using import

I am baffled.

Node v16.20.2

package.json

{
  "private": true,
  "name": "baffled-i-tell-you",
  "version": "0.1.0",
  "main": "index.js",
  "devDependencies": {
    "@babel/core": "^7.24.4",
    "@babel/preset-env": "^7.24.4",
    "@cloudflare/wrangler": "^1.12.0",
    "babel-jest": "^29.7.0",
    "jest": "^29.7.0",
    "node-fetch": "^3.3.2"
  },
  "scripts": {
    "test": "jest"
  }
}

babel.config.js

module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          node: 'current',
        },
      },
    ],
  ],
  env: {
    test: {
      presets: [
        ['@babel/preset-env', { targets: { node: 'current' } }],
      ],
    },
  },
};

jest.config.js

const config = {
  testEnvironment: './tests/config/FixGlobalsEnvironment.js',
  transform: {
    "^.+\.js$": "babel-jest",
  },
  globals: {
    addEventListener: () => {} // Used in main piece of code, but not for testing
  }
};

module.exports = config;

FixGlboalsEnvironment.js

import fetch, {Headers, Request, Response} from "node-fetch";
import NodeEnvironment from 'jest-environment-node';

export default class FixGlobalsEnvironment extends NodeEnvironment {
    constructor(...args) {
        super(...args);

        this.global.fetch = fetch;
        this.global.Headers = Headers;
        this.global.Request = Request;
        this.global.Response = Response;
    }
}

Result when executing yarn test:

    Error [ERR_REQUIRE_ESM]: require() of ES Module /home/joy/.../node_modules/node-fetch/src/index.js from /home/joy/.../tests/config/FixGlobalsEnvironment.js not supported.

    Instead change the require of index.js in /home/joy/.../tests/config/FixGlobalsEnvironment.js to a dynamic import() which is available in all CommonJS modules.

       6 |         super(...args);
       7 |
    >  8 |         this.global.fetch = fetch;
         |                                          ^
       9 |         this.global.Headers = Headers;
      10 |         this.global.Request = Request;
      11 |         this.global.Response = Response;

      at Object.newLoader [as .js] (node_modules/pirates/lib/index.js:121:7)
      at Object.<anonymous> (tests/config/FixGlobalsEnvironment.js:8:42)
      at Module._compile (node_modules/pirates/lib/index.js:117:24)
      at Object.newLoader [as .js] (node_modules/pirates/lib/index.js:121:7)
          at async Promise.all (index 0)
      at async ScriptTransformer.requireAndTranspileModule (node_modules/@jest/transform/build/ScriptTransformer.js:798:22)

I am utterly confused at the message: Instead change the require of index.js in /home/joy/.../tests/config/FixGlobalsEnvironment.js to a dynamic import() which is available in all CommonJS modules.

Clearly I have messed up the configuration between babel and jest, but I don’t know where I have messed it up.

  • I am using the polyfill solution because “node” environment doesn’t have Headers, Response, Request. Main code tested is not running in a browser environment. When I try running this with default “node” environment:

Headers is not defined on default "node" environment

  • Using node-fetch v2 I get this error: (when I have polyfilled it…)
TypeError: Class constructor Request cannot be invoked without 'new'

       8 |         headers.append('Content-Type', 'application/json');
       9 |
    > 10 |         return new Request(url, {
         |                ^
      11 |             method: 'GET',
      12 |             headers
      13 |         });

      at mockConstructor.<anonymous> (node_modules/jest-mock/build/index.js:794:25)
      at getRequestMock (tests/index.test.js:10:16)
      at getRequestMock (tests/index.test.js:23:45)
      at call (tests/index.test.js:2:1)
      at Generator.tryCatch (tests/index.test.js:2:1)
      at Generator._invoke [as next] (tests/index.test.js:2:1)

  • The cherry on top, if I remove everything, and leave environment on “node” but run the test from my IDE (PHPStorm)… it works great, all test pass accordingly, no problems with set up.

  • I have added transformIgnorePatterns: [], to my jest.config.js as I saw others do, but it did not work.

  • I have removed also removed jest.config.js in favour of only having babel.config.js. Of course I lose the possibility of doing the polyfill in a nice way through jest.config.js so I have to create a file that has this code (I import the file as the first import on my tests).

import fetch, {Headers, Request, Response} from "node-fetch";

global.addEventListener = () => {};
global.fetch = fetch;
global.Headers = Headers;
global.Request = Request;
global.Response = Response;

Still doesn-t work, error is now:

 TypeError: Class constructor Request cannot be invoked without 'new'

      12 |         headers.append('Content-Type', 'application/json');
      13 |
    > 14 |         return new Request(url, {
         |                ^
      15 |             method: 'GET',
      16 |             headers
      17 |         });

      at mockConstructor.<anonymous> (node_modules/jest-mock/build/index.js:794:25)
      at getRequestMock (tests/index.test.js:14:16)
      at getRequestMock (tests/index.test.js:27:45)

I really didn’t think it would be this hard to add jest.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật