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

使用Serverless+TypeScript+Jest测试时遇‘Cannot find module’错误排查

问题原因及修复方案

出现Cannot find module '@functions/hello/handler'的核心原因是Jest默认不识别TypeScript的路径别名,同时TS配置与Jest配置未正确关联,导致模块解析失败。以下是具体排查和修复步骤:

1. 检查TypeScript路径别名配置

确认tsconfig.paths.json的别名映射指向实际文件目录,配置示例:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@functions/*": ["src/functions/*"]
    }
  }
}

注意:替换src/functions/*为你项目中hello handler所在的真实路径,比如functions文件夹在根目录下就写["functions/*"]。

2. 让主TS配置继承路径规则

在tsconfig.json中加入extends字段,引入tsconfig.paths.json的配置,确保TypeScript编译器能识别别名:

{
  "extends": "./tsconfig.paths.json",
  // 保留原有compilerOptions配置
  "include": ["src/**/*"]
}

3. 配置Jest解析路径别名

修改jest.config.js,添加moduleNameMapper映射别名到真实路径,同时配置ts-jest预设支持TypeScript测试:

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  // 映射@functions别名到实际目录
  moduleNameMapper: {
    '^@functions/(.*)$': '<rootDir>/src/functions/$1'
  },
  moduleFileExtensions: ['ts', 'js'],
  rootDir: '.'
};

<rootDir>对应Jest根目录,需与tsconfig.paths.json的baseUrl保持一致,路径部分要和TS配置的paths匹配。

4. 安装必要依赖

若未安装相关依赖,执行以下命令补装:

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

5. 验证测试文件导入

确保测试文件(比如hello.test.ts)的导入语句与别名配置一致:

import { handler } from '@functions/hello/handler';

完成以上配置后,重新运行jest --config=jest.config.js即可解决模块找不到的问题。

内容的提问来源于stack exchange,提问作者Wai Yan Hein

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 03:09:59