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

Jest无法识别Awilix容器,ES模块导入报错求助

解决Jest中Awilix ES模块导入报错问题

问题分析

你使用tsc配置"module": "es2022"构建项目,运行npx jest时触发TypeError: Cannot read properties of undefined (reading 'createContainer'),错误指向Setup.ts里的awilix.createContainer调用。手动将编译后的Setup.js中ES模块导入改为const awilix = require('awilix')后测试正常,但Express的ES导入无异常——这是因为Awilix的ES模块导出逻辑与Jest当前的模块处理机制不兼容,或是TypeScript编译后的ES模块在Jest的CommonJS运行环境中未被正确转换。

解决方案

方案1:修改Awilix的导入方式

将默认导入改为命名空间导入,部分库的ES模块导出在CommonJS环境中会被包裹在default属性下,命名空间导入可直接获取完整导出对象:

// Setup.ts
import * as awilix from 'awilix';

const container = awilix.createContainer({
  injectionMode: awilix.InjectionMode.CLASSIC
});

方案2:调整Babel与Jest配置

当前babel.config.cjs仅启用了CommonJS转换插件,需补充默认导出处理插件,同时完善Jest的转换配置:

  1. 更新babel.config.cjs:
module.exports = {
  plugins: [
    '@babel/plugin-proposal-export-default-from',
    '@babel/plugin-transform-modules-commonjs'
  ],
  presets: [['@babel/preset-env', { targets: { node: 'current' } }]]
};
  1. 更新jest.config.cjs,启用ES模块支持并明确转换规则:
module.exports = {
  globals: {
    "ts-jest": {
      isolatedModules: true,
      useESM: true
    },
  },
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
  },
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
};

方案3:修正TypeScript编译配置

确保tsconfig.json的模块解析策略与"module": "es2022"匹配,开启ES模块与CommonJS的互支持:

{
  "compilerOptions": {
    "module": "es2022",
    "moduleResolution": "node16", // 或nodenext,与module配置对应
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true
  }
}

方案4:切换Jest为ES模块模式

若你的Node.js版本≥16,可将Jest配置改为ES模块格式(jest.config.mjs),并开启项目的ES模块模式:

  1. 创建jest.config.mjs:
export default {
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
  },
  extensionsToTreatAsEsm: ['.ts'],
  moduleNameMapper: {
    '^(\\.{1,2}/.*)\\.js$': '$1', // 处理TypeScript导入时的.js后缀
  },
};
  1. 在package.json中添加:
"type": "module"

验证

修改配置后,重新执行tsc编译项目,再运行npx jest,确认awilix.createContainer不再抛出错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 05:24:27