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

React项目非src目录下TypeScript代码的Jest测试配置问题

解决CRA TypeScript项目中Server目录Jest测试及nanoid模块问题

1. 用CRA自带Babel配置处理Server目录TypeScript

不用额外安装ts-jest,直接复用CRA已配置好的Babel环境编译TypeScript:

  • 在项目根目录新建jest.config.js,写入以下配置:
module.exports = {
  // 指定Jest仅扫描server目录的测试文件
  roots: ['<rootDir>/server'],
  // 用CRA自带的Babel转换器处理TS/TSX文件
  transform: {
    '^.+\\.(ts|tsx)$': '<rootDir>/node_modules/react-scripts/config/jest/babelTransform.js',
  },
  // 声明支持的文件扩展名
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
};
  • 修改package.json中的测试脚本:
"scripts": {
  // ...保留原有其他脚本
  "test-server": "jest --config jest.config.js"
}

2. 修复nanoid的ES模块导入错误

nanoid采用纯ES模块编写,Jest默认会跳过node_modules目录的代码转换,导致出现SyntaxError: Cannot use import statement outside a module。只需修改jest.config.js,让Babel也处理nanoid:

module.exports = {
  roots: ['<rootDir>/server'],
  transform: {
    '^.+\\.(ts|tsx)$': '<rootDir>/node_modules/react-scripts/config/jest/babelTransform.js',
  },
  // 排除node_modules中除nanoid外的其他模块,让Babel转换nanoid的ES语法
  transformIgnorePatterns: [
    '[/\\\\]node_modules[/\\\\](?!nanoid).+\\.(js|jsx|mjs|cjs|ts|tsx)$',
  ],
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
};

如果src目录的测试也遇到相同的nanoid问题,可在package.json中添加Jest扩展配置,覆盖CRA默认设置:

"jest": {
  "transformIgnorePatterns": [
    "[/\\\\]node_modules[/\\\\](?!nanoid).+\\.(js|jsx|mjs|cjs|ts|tsx)$"
  ]
}

3. 运行测试

执行npm run test-server即可正常运行server目录下的TypeScript测试,同时解决nanoid的导入报错。

内容的提问来源于stack exchange,提问作者John Tang Boyland

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 14:05:38