使用TypeScript+ESM+Jest测试时无法找到@middy/core模块
解决方案:TypeScript+ESM+Jest测试Middy Lambda的模块找不到问题
1. 确认依赖安装完整
先确保安装了Middy核心包及Jest相关TS依赖:
npm install @middy/core npm install -D jest typescript ts-jest @types/jest @types/node
注意:@middy/core v4及以上版本自带TypeScript类型声明,无需额外安装@types/middy;若使用旧版本,需补充安装@types/middy。
2. 修正Jest配置(适配ESM+TS)
如果是ESM格式的jest.config.ts,调整为如下配置:
export default { preset: 'ts-jest/presets/default-esm', testEnvironment: 'node', extensionsToTreatAsEsm: ['.ts'], moduleNameMapper: { '^(\\.{1,2}/.*)\\.js$': '$1' }, transform: { '^.+\\.tsx?$': [ 'ts-jest', { useESM: true, tsconfig: './tsconfig.json' } ] }, globals: { 'ts-jest': { useESM: true } }, clearMocks: true }
如果是CommonJS格式的jest.config.js,将export default替换为module.exports即可。
3. 调整TypeScript配置
确保tsconfig.json兼容ESM和Node环境:
{ "compilerOptions": { "target": "ES2020", "module": "ESNext", "moduleResolution": "NodeNext", "esModuleInterop": true, "skipLibCheck": true, "strict": true, "outDir": "./dist", "types": ["jest", "node"] }, "include": ["src/**/*", "__tests__/**/*"], "exclude": ["node_modules"] }
关键配置说明:
moduleResolution: "NodeNext":适配Node的ESM模块解析规则types: ["jest", "node"]:解决jest全局变量未定义的问题skipLibCheck: true:跳过第三方库类型检查,避免Middy类型声明冲突
4. 规范测试文件的ESM写法
测试文件需使用ESM的import语法,若需使用jest全局方法,二选一即可:
- 在测试文件顶部显式导入:
import { jest, describe, test, expect } from '@jest/globals' - 依赖Jest全局注入(需确保jest.config的
globals配置正确)
5. 修复package.json配置
在package.json中添加"type": "module",确保Node默认使用ESM模式:
{ "type": "module", "scripts": { "test": "jest" } }
Node 20.9.0已默认支持ESM,无需在test脚本中添加--experimental-vm-modules参数。
6. 示例Handler与测试代码
Handler代码(src/handler.ts)
import middy from '@middy/core' const baseHandler = async (event: any) => { return { statusCode: 200, body: JSON.stringify({ message: 'Hello' }) } } export const handler = middy(baseHandler)
测试代码(tests/handler.test.ts)
import { handler } from '../src/handler' describe('Lambda Handler', () => { test('returns successful response', async () => { const event = {} const result = await handler(event, {} as any, () => {}) expect(result.statusCode).toBe(200) }) })
补充排查:"jest is not defined"问题
若之前调整配置后出现此错误:
- 检查tsconfig的
types数组是否包含"jest" - 确认jest.config中
globals['ts-jest'].useESM设为true - 避免在测试文件中混用CommonJS的
require和ESM的import
内容的提问来源于stack exchange,提问作者phau-heinan
相关产品推荐
相关产品推荐

