Monorepo下ts-jest运行Middy测试报core_1.default非函数错误
问题背景
我基于Lerna和yarn workspace搭建了TypeScript Monorepo项目,项目包含一套AWS API Gateway接口,后端由多个Lambda函数实现,这些Lambda使用Middy完成CORS处理、超时控制等逻辑。项目使用Jest配合ts-jest为Lambda函数编写、运行单元测试,在运行首个Lambda测试用例时出现报错。
此前已尝试在子包tsconfig.json的compilerOptions段、根目录tsconfig.json、Jest专用自定义tsconfig.json中添加"esmoduleInterop": true配置,均未解决问题。
报错信息
FAIL packages/announcer/test/api/list-non-compliant-rules.test.ts ● Test suite failed to run TypeError: core_1.default is not a function 97 | } 98 | > 99 | export const handler = middy(main, { | ^ 100 | timeoutEarlyInMillis: TIMEOUT, 101 | timeoutEarlyResponse: () => { 102 | Log.error(`Timeout of ${TIMEOUT}ms exceeded`) at Object.<anonymous> (lambda/api/list-non-compliant-rules.ts:99:29) at Object.<anonymous> (test/api/list-non-compliant-rules.test.ts:4:36)
相关代码与配置
- Middy导入方式
import middy from "@middy/core"
- Middy使用方式
export const handler = middy(main, { timeoutEarlyInMillis: TIMEOUT, timeoutEarlyResponse: () => { Log.error(`Timeout of ${TIMEOUT}ms exceeded`) return internalServerError(new Error("Timeout")) }, }) .use(cors()) .use(httpErrorHandler()) .use( httpContentNegotiation({ availableLanguages: ["en-US"], availableMediaTypes: ["application/vnd.api+json"], }) )
- 子包
tsconfig.json配置
{ "extends": "../../tsconfig.json", "compilerOptions": { "types": ["node", "jest"], "esModuleInterop": true, }, "exclude": ["node_modules", "cdk.out"] }
- 根目录
tsconfig.json配置
{ "compilerOptions": { "target": "ES2018", "module": "commonjs", "lib": ["es2018"], "declaration": true, "strict": true, "noImplicitAny": true, "strictNullChecks": true, "noImplicitThis": true, "alwaysStrict": true, "noUnusedLocals": false, "noUnusedParameters": false, "noImplicitReturns": true, "noFallthroughCasesInSwitch": false, "inlineSourceMap": true, "inlineSources": true, "experimentalDecorators": true, "strictPropertyInitialization": false, "typeRoots": ["./node_modules/@types"], "esModuleInterop": true }, }
解决方案
核心问题是配置拼写错误+ts-jest未正确加载TS编译配置,按以下步骤排查修复:
- 修正TS配置项拼写
之前添加的esmoduleInterop是错误拼写,正确配置名是**esModuleInterop**,其中Module的首字母M必须大写,错误拼写会导致TS编译器完全忽略该配置,默认导入兼容逻辑不生效,才会出现core_1.default is not a function的错误。 - 补充配套TS配置
在根、子包tsconfig.json的compilerOptions中同步添加"allowSyntheticDefaultImports": true,和esModuleInterop配合,确保CommonJS模块的默认导入逻辑正常工作。 - 显式配置ts-jest读取的tsconfig路径
检查Jest配置文件,避免ts-jest使用内置默认配置忽略项目中的TS配置,尤其在Monorepo场景下必须显式指定配置路径,示例配置片段:
// jest.config.js module.exports = { preset: 'ts-jest', testEnvironment: 'node', transform: { '^.+\\.tsx?$': ['ts-jest', { tsconfig: '<rootDir>/tsconfig.json' // 对应指向项目实际的tsconfig路径 }] } }
- 清理缓存验证
执行测试前先运行npx jest --clearCache清除旧的编译缓存,避免历史缓存导致新配置不生效。 - 兼容方案(以上步骤无效时使用)
直接调整Middy的导入方式适配CommonJS规范,替换原有默认导入语句:
// 替换 import middy from "@middy/core" import * as middy from "@middy/core"
内容的提问来源于stack exchange,提问作者Aurelia Peters
相关产品推荐
相关产品推荐

