是否有一种方法可以为单个文件而不是整个测试套件运行ng test ?理想情况下,我希望在编辑文件时获得尽可能快的反馈循环,但karma在每次保存时执行整个套件,当您构建足够大的测试套件时,这有点慢。


这与如何使用angular-cli只执行一个测试规范不同,因为那个问题是关于运行一个单独的规范。这是关于运行一个单独的文件。解决方案涉及相同的Jasmine规范特性,但问题的性质略有不同。


当前回答

你可以访问src/test。Ts和可以更改以下行:

Const context = require.context('。/', true, /\.spec\.ts$/);

to

Const context = require.context('。/”,的确,/ * * yourcomponent.component * * \ .spec \ .ts /美元);

其他回答

如果将规范文件指定为参数,则有效。

例如:

ng test foo.spec.ts

获取测试文件的相对路径并像这样提供

ng test --include=src\app\app.component.spec.ts

这对我有用!!

Visual Studio代码扩展

最简单的方法是使用vcode -test-explorer扩展及其子angular-karma-test-explorer和jasmine-test-adapter,如果你想,你会得到一个当前测试的列表,一个接一个地运行:

这和我回答这个问题时的答案是一样的,还有更多细节。


更新DEC/2021: Angular Karma Test Explorer已弃用,请考虑使用Karma Test Explorer

如果您正在使用IntelliJ IDE,您可以安装“Karma”插件,并通过单击spec测试旁边的“运行”图标单独运行spec

我发现ng test有一个额外的选项——include,你可以使用它来对单个文件或特定目录或一堆文件运行测试:

// one file
npm run test -- --include src/app/components/component/component-name.component.spec.ts

// directory or bunch of files
npm run test -- --include src/app/components

Ng cli文档