我正在尝试使用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风格的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
这将产生以下Jest配置:
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
};
1条答案
按热度按时间fwzugrvs1#
请使用与CommonJS兼容的v2: