在 Jest 和 Typescript 中使用 node-fetch 时出现错误“SyntaxError: Cannot use import statements Outside a module”

dev*_*obf 10 typescript jestjs node-fetch

我正在尝试使用 Jest 在 Typescript 中编写集成测试node-fetch,如下所示:

import fetch from 'node-fetch';

test('Hello', async () => {
    await fetch("http://www.google.com");
});
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误:

    Jest encountered an unexpected token

    [...]
    
    Details:

    /home/xxx/node_modules/node-fetch/src/index.js:9
    import http from 'node:http';
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module

    > 1 | import fetch from 'node-fetch';
        | ^
      2 |
      3 | test('Hello', async () => {
      4 |     await fetch("http://www.google.com");

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)
      at Object.<anonymous> (temp.test.ts:1:1)
Run Code Online (Sandbox Code Playgroud)

我已经尝试过其他问题中给出的一些解决方案,但它们不起作用;我认为我的问题略有不同,因为一般来说并不妨碍我使用 ES6 风格的 important,但它特别不适用于node-fetch. 例如,我可以import express from 'express'毫无困难地做到这一点。

为了重现此错误,我运行了:

npm init
npm install --save-dev jest typescript ts-jest @types/jest node-fetch @types/node-fetch
npx ts-jest config:init
npx jest
Run Code Online (Sandbox Code Playgroud)

生成以下 Jest 配置:

    Jest encountered an unexpected token

    [...]
    
    Details:

    /home/xxx/node_modules/node-fetch/src/index.js:9
    import http from 'node:http';
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module

    > 1 | import fetch from 'node-fetch';
        | ^
      2 |
      3 | test('Hello', async () => {
      4 |     await fetch("http://www.google.com");

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)
      at Object.<anonymous> (temp.test.ts:1:1)
Run Code Online (Sandbox Code Playgroud)

小智 22

请使用与 CommonJS 保持兼容的 v2:

npm install node-fetch@2
Run Code Online (Sandbox Code Playgroud)
const fetch = require('node-fetch');
Run Code Online (Sandbox Code Playgroud)