Angular 16迁移Jest遇aws-amplify转译及transformIgnorePatterns报错
解决方案:Angular 16 + Jest + AWS Amplify 转译错误修复
1. 修正 Jest 配置中的 transformIgnorePatterns
问题根源是添加转译忽略规则后,Jest未正确处理jest-preset-angular和AWS Amplify的ES模块文件。调整规则,让Jest转译所有@aws-amplify相关包,同时确保jest-preset-angular文件不被误忽略:
修改jest.config.js:
module.exports = { preset: 'jest-preset-angular', globalSetup: 'jest-preset-angular/global-setup', setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'], transform: { '^.+\\.(ts|js|mjs|html)$': 'jest-preset-angular', }, transformIgnorePatterns: [ 'node_modules/(?!(@aws-amplify|aws-amplify)/)', ], moduleFileExtensions: ['ts', 'js', 'html'], };
2. 确保测试配置文件的一致性
- 把
setup-jest.js重命名为setup-jest.ts(已存在则跳过),并在tsconfig.spec.json中明确包含该文件:
{ "extends": "./tsconfig.json", "compilerOptions": { "outDir": "./out-tsc/spec", "module": "CommonJS", "types": ["jest", "node"] }, "include": [ "src/**/*.spec.ts", "src/**/*.d.ts", "setup-jest.ts" ] }
- 确认
tsconfig.json的module字段设为ESNext或ES2020,tsconfig.spec.json的module设为CommonJS(匹配Jest默认模块规范)。
3. 对齐依赖版本
确保核心依赖版本兼容Angular 16:
jest-preset-angular>= 14.0.0jest>= 29.0.0@aws-amplify/ui-angular>= 5.0.0
执行命令更新依赖:
npm install jest-preset-angular@latest jest@latest @types/jest@latest --save-dev npm install @aws-amplify/ui-angular@latest aws-amplify@latest --save
4. 清除Jest缓存
缓存可能导致配置不生效,执行:
npx jest --clearCache
之后重新运行测试即可。
排查补充
- 若仍出现
Cannot use import statement outside a module:检查setup-jest.ts路径是否在jest.config.js的setupFilesAfterEnv中正确配置,且已被tsconfig.spec.json包含。 - 若AWS Amplify转译错误未解决:扩展
transformIgnorePatterns,把所有关联子包加入转译范围,比如node_modules/(?!(@aws-amplify|@aws-amplify/core|@aws-amplify/auth)/)。
内容的提问来源于stack exchange,提问作者Charlie
相关产品推荐
相关产品推荐

