Angular 18库项目:ng test无法找到Spec文件问题求助
解决Angular库项目
ng test找不到测试用例的问题 针对运行ng test library返回Executed 0 of 0 SUCCESS的问题,可按以下步骤排查:
检查tsconfig.spec.json的路径覆盖
确保projects/library/tsconfig.spec.json的include字段覆盖所有测试文件路径。如果库是嵌套组件结构,路径需包含子目录:{ "extends": "./tsconfig.lib.json", "compilerOptions": { "outDir": "../../out-tsc/spec", "types": ["jasmine"] }, "include": ["**/*.spec.ts", "**/*.d.ts"] }注意路径是相对于该配置文件的位置,若测试文件在
projects/library/button/src/下,**/*.spec.ts会递归匹配所有子目录的测试文件。验证angular.json的test配置
检查库项目的test配置是否明确指定测试文件范围,同时确认test.ts路径正确:"test": { "builder": "@angular-devkit/build-angular:karma", "options": { "main": "projects/library/src/test.ts", "tsConfig": "projects/library/tsconfig.spec.json", "karmaConfig": "projects/library/karma.conf.js", "include": ["projects/library/**/*.spec.ts"] } }另外,确认
test.ts文件中存在自动加载测试的代码:declare const require: { context(path: string, deep?: boolean, filter?: RegExp): { keys(): string[]; <T>(id: string): T; }; }; const context = require.context('./', true, /\.spec\.ts$/); context.keys().map(context);若
test.ts缺失或路径错误,会导致无法加载测试文件。检查测试文件的合规性
- 确保所有测试文件以
.spec.ts结尾,无拼写错误(如误写为.test.ts)。 - 排查测试文件的语法错误,比如导入路径错误、未闭合的代码块等,这类问题会导致Karma跳过测试。
- 确保所有测试文件以
清理缓存并重新构建
- 运行
ng cache clean清理Angular缓存,再执行ng test library。 - 若问题仍存在,删除
node_modules和package-lock.json,重新执行npm install后再测试。
- 运行
检查Karma配置
打开projects/library/karma.conf.js,确认files配置指向正确的test.ts文件:files: [ { pattern: './src/test.ts', watched: false } ], preprocessors: { './src/test.ts': ['webpack', 'sourcemap'] }确保没有额外的
exclude规则过滤掉测试文件。
内容的提问来源于stack exchange,提问作者Eric R
相关产品推荐
相关产品推荐

