使用Typescript中的Jest和node-fetch时出现错误 "SyntaxError: Cannot use import statement outside a module"。

8

我正在尝试使用Jest和Typescript编写一个集成测试,其中需要使用node-fetch,代码如下:

import fetch from 'node-fetch';

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

但我遇到了以下错误:

    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)

我已经尝试了其他问题中提供的一些解决方案,但它们都不起作用。我认为我的问题略有不同,因为它不会阻止我在一般情况下使用ES6风格的重要性,但它特别对于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

这将产生以下的Jest配置:

/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
};

很遗憾,这不起作用 - 它会给出错误Cannot redeclare block-scoped variable 'fetch'.ts(2451), lib.dom.d.ts(18095, 18): 'fetch' was also declared here.即使我给它一个不同的名字,它仍然不起作用。 - devrobf
node-fetch v3现在分发ES模块。如果你使用CommonJS,你将不得不降级到v2。 - jonrsharpe
如果有其他人也遇到了这个问题 - 我最终降级到了v2的node fetch。我找不到其他解决方案。 - devrobf
如果无法重新声明 fetch,请尝试使用 const nodeFetch = require("node-fetch"),然后 await nodeFetch("...") - mathletedev
@mathletedev,对我来说也不起作用。 - devrobf
显示剩余3条评论
1个回答

20
请使用与CommonJS兼容的v2版本:
npm install node-fetch@2

const fetch = require('node-fetch');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接