错误“语法错误:在Jest中使用带Typescript的node-fetch时,无法在模块“”之外使用import语句

2ic8powd  于 2023-06-20  发布在  Jest
关注(0)|答案(1)|浏览(165)

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

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

但我得到了以下错误:

  1. Jest encountered an unexpected token
  2. [...]
  3. Details:
  4. /home/xxx/node_modules/node-fetch/src/index.js:9
  5. import http from 'node:http';
  6. ^^^^^^
  7. SyntaxError: Cannot use import statement outside a module
  8. > 1 | import fetch from 'node-fetch';
  9. | ^
  10. 2 |
  11. 3 | test('Hello', async () => {
  12. 4 | await fetch("http://www.google.com");
  13. at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)
  14. at Object.<anonymous> (temp.test.ts:1:1)

我已经尝试了其他问题中给出的一些解决方案,但它们不起作用;我认为我的问题略有不同,因为一般来说,它 * 并不 * 阻止我使用ES6风格的important,但它 * 特别 * 不适用于node-fetch。例如,我可以毫不费力地做import express from 'express'
为了重现这个错误,我运行:

  1. npm init
  2. npm install --save-dev jest typescript ts-jest @types/jest node-fetch @types/node-fetch
  3. npx ts-jest config:init
  4. npx jest

这将产生以下Jest配置:

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

fwzugrvs1#

请使用与CommonJS兼容的v2:

  1. npm install node-fetch@2
  1. const fetch = require('node-fetch');

相关问题