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

Jest+TypeScript+AWS Lambda及Layer测试模块导入问题

Jest + TypeScript 环境测试Lambda Layer模块导入失败解决方案

问题背景

项目文件结构如下:

backend/
├─ jest.config.js
├─ package.json
├─ babel.config.js
├─ layers/
│  ├─ tsconfig.json
│  ├─ aws_handler/
├─ lambdas/
│  ├─ tsconfig.json
│  ├─ some_lambda/
│  │  ├─ index.ts
├─ tests/
│  ├─ tsconfig.json
│  ├─ some_lambda.test.ts

运行npm test时触发错误:

Cannot find module '@libs/aws' or its corresponding type declarations

Lambda正常运行时,可通过import { lambda } from '@libs/aws';导入Layer,且lambdas/tsconfig.json已配置路径映射:

"baseUrl": "",
"paths": {
  "@libs/aws": [
    "../layers/aws_handler"
  ]
}

测试阶段Jest无法识别该路径映射,尝试配置modulePaths、moduleDirectories未解决问题。

可行解决方案

1. 复用TypeScript路径映射(推荐)

借助ts-jest的pathsToModuleNameMapper工具,直接读取lambdas/tsconfig.json中的路径配置,避免重复编写映射规则:

先安装依赖:

npm install --save-dev ts-jest @types/jest

修改jest.config.js:

const { pathsToModuleNameMapper } = require('ts-jest');
const { compilerOptions } = require('./lambdas/tsconfig.json');

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  rootDir: './',
  moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, {
    prefix: '<rootDir>/'
  }),
  // 保留其他原有配置
};

注意:若lambdas/tsconfig.json中的baseUrl不为空,需调整prefix参数匹配实际路径前缀。

2. 手动配置Jest模块映射

无需依赖工具的话,可直接在jest.config.js中手动声明路径映射:

module.exports = {
  // 其他配置
  moduleNameMapper: {
    '^@libs/aws$': '<rootDir>/layers/aws_handler'
  }
};

3. 统一根目录TypeScript配置

在项目根目录创建tsconfig.json,整合路径规则,让测试目录继承该配置:

根目录tsconfig.json:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@libs/aws": ["./layers/aws_handler"]
    }
  },
  "include": ["lambdas/**/*", "tests/**/*"]
}

tests/tsconfig.json修改为:

{
  "extends": "../tsconfig.json",
  // 测试专属配置
}

更新jest.config.js指定根目录TypeScript配置:

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  rootDir: './',
  globals: {
    'ts-jest': {
      tsconfig: './tsconfig.json'
    }
  }
};

4. 检查路径拼写

确认lambdas/tsconfig.json中的路径是../layers/aws_handler,而非原描述中的../lambda_layers/aws_handler(根据文件结构,Layer目录为layers,拼写错误会导致路径无法识别)。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 04:55:17