You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用TypeScript、Jest与Got编写API测试时遇import语法错误求助

解决Jest+TypeScript+Got的「SyntaxError: Cannot use import statement outside a module」错误

问题根源

你的项目启用了ES模块(package.json中"type": "module"),但默认的ts-jest预设针对CommonJS环境,而Got v12是纯ES模块,两者的模块系统冲突导致解析失败。移除Got的import后Jest正常工作,说明核心问题是ES模块兼容性配置缺失。

修复步骤

1. 更新jest.config.js配置

修改为ES模块适配的配置:

export default {
  preset: 'ts-jest/presets/default-esm',
  moduleNameMapper: {
    '^(\\.{1,2}/.*)\\.js$': '$1',
  },
  transform: {
    '^.+\\.tsx?$': ['ts-jest', {
      useESM: true,
    }],
  },
  setupFilesAfterEnv: ["@testing-library/jest-dom"],
  extensionsToTreatAsEsm: ['.ts'],
};
  • preset: 'ts-jest/presets/default-esm':切换到ES模块专用预设
  • useESM: true:指示ts-jest生成ES模块代码
  • moduleNameMapper:处理ES模块导入时必须添加的.js后缀问题
  • extensionsToTreatAsEsm:将.ts文件标记为ES模块

2. 配置TypeScript(tsconfig.json)

如果没有该文件,先创建,确保包含以下核心配置:

{
  "compilerOptions": {
    "module": "ESNext",
    "target": "ES2020",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["tests/**/*"]
}
  • module: "ESNext":指定编译输出为ES模块
  • moduleResolution: "node":使用Node.js的模块解析逻辑

3. 修改测试脚本

添加Node.js支持ES模块的实验性参数:

{
  "scripts": {
    "test-gotjest": "NODE_OPTIONS=--experimental-vm-modules npx jest ./tests/gotjest"
  }
}

--experimental-vm-modules是Node.js在Jest环境中启用ES模块支持的必要参数。

4. 优化测试代码(可选但推荐)

Got的请求是异步操作,建议改成异步测试:

import { got } from "got";
import { describe, expect, test } from '@jest/globals';

describe('see if got works', () => {
  test('get a cat fact', async () => {
    const response = await got.get('https://catfact.ninja/fact');
    expect(response.statusCode).toBe(200);
    expect(JSON.parse(response.body)).toHaveProperty('fact');
  });
});

完成以上配置后,重新执行npm run test-gotjest即可正常运行测试。

内容的提问来源于stack exchange,提问作者Huckleberry Carignan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 05:00:59