Angular组件Jest测试运行失败,报错无法加载html文件怎么解决?
报错的核心原因是HTML模板文件没有被正确转换为内联字符串,Angular测试运行时尝试通过HTTP请求加载本地HTML模板,因此触发127.0.0.1:80连接拒绝的报错。
解决方案
1. 修正jest.config.js配置
当前transform配置仅使用ts-jest,没有正确处理Angular组件的HTML模板转换,修改对应配置项如下:
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */ module.exports = { preset: "jest-preset-angular", testEnvironment: "jsdom", setupFilesAfterEnv: ["<rootDir>/setup-jest.ts"], globals: { "ts-jest": { tsconfig: "<rootDir>/tsconfig.spec.json", stringifyContentPathRegex: "\\.(html|svg)$", }, }, snapshotSerializers: [ "jest-preset-angular/build/serializers/html-comment", "jest-preset-angular/build/serializers/ng-snapshot", "jest-preset-angular/build/serializers/no-ng-attributes", ], moduleDirectories: ["node_modules", "."], testMatch: ["**/+(*.)+(spec|test).+(ts|js)?(x)"], // 替换原来的transform配置,使用jest-preset-angular处理全类型文件 transform: { "^.+\\.(ts|js|html|svg)$": "jest-preset-angular", }, resolver: "@nrwl/jest/plugins/resolver", moduleFileExtensions: ["ts", "js", "html", "svg"], coverageReporters: ["html"], // 若你在tsconfig中配置了路径别名,需要补充对应moduleNameMapper配置 // moduleNameMapper: { // '^@/(.*)$': '<rootDir>/src/$1' // } };
2. 补充tsconfig.spec.json配置
在compilerOptions同级新增Ivy编译适配配置:
{ "extends": "./tsconfig.json", "compilerOptions": { "outDir": "./out-tsc/spec", "module": "commonjs", "types": ["jest", "node"], "allowJs": true, "esModuleInterop": true, "emitDecoratorMetadata": true }, // 新增以下配置 "angularCompilerOptions": { "enableIvy": true, "compilationMode": "partial" }, "files": ["setup-jest.ts"], "include": ["src/**/*.spec.ts", "src/**/*.d.ts"] }
3. 安装缺失依赖
Jest 27版本开始不再内置jsdom测试环境,需安装对应版本的依赖:
npm install -D jest-environment-jsdom@27.2.4
4. 清理缓存运行测试
修改配置后先清理 Jest 缓存,避免旧缓存导致配置不生效:
npx jest --clearCache && npm run test
内容的提问来源于stack exchange,提问作者pajevic
相关产品推荐
相关产品推荐

