我正在尝试使用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.
即使我给它一个不同的名字,它仍然不起作用。 - devrobffetch
,请尝试使用const nodeFetch = require("node-fetch")
,然后await nodeFetch("...")
。 - mathletedev