Angular 13使用ng test --include指定测试文件失效问题求助
问题分析与解决方法
你的问题出在两个核心点:test.ts里的正则表达式错误,以及手动加载所有测试文件的逻辑导致--include参数失效。
1. 修正test.ts的正则表达式错误
你当前test.ts里的正则/\.spec\ts$/是错误的:\t是制表符的转义字符,这个正则会匹配.spec后跟制表符再以s结尾的文件,完全不符合匹配.spec.ts测试文件的需求。正确的正则应该是:
const context = require.context('./', true, /\.spec\.ts$/);
2. 让--include参数真正生效
你手动在test.ts里用require.context遍历加载所有测试文件的行为,会绕过Angular CLI的--include过滤逻辑——不管CLI指定了哪些文件,test.ts都会加载所有符合正则的测试文件,导致所有测试被执行。
解决方法是修改test.ts,让它只在没有通过--include指定测试文件时,才加载全部测试文件:
declare const __karma__: any; // 仅当没有指定--include时,才加载全部测试文件 if (!__karma__.config.files || __karma__.config.files.every(file => file.includes('test.ts'))) { const context = require.context('./', true, /\.spec\.ts$/); context.keys().map(context); }
3. 命令行参数的正确写法
- 运行单个测试文件:
npx ng test --include src/app/services/mySharedService.spec.ts
- 运行多个测试文件(用多个
--include参数):
npx ng test --include src/app/services/mySharedService.spec.ts --include src/app/components/myComponent.spec.ts
- 匹配services目录下所有测试文件:
npx ng test --include "**/services/*.spec.ts"
注意:不要用[]包裹路径,shell会将方括号解析为通配符,导致路径匹配失败。
完成以上修改后,--include参数就能正常生效,只运行你指定的测试文件了。
内容的提问来源于stack exchange,提问作者fumeng
相关产品推荐
相关产品推荐

