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


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


当前回答

你必须去src/test。Ts和可以更改以下行号代码18:

//Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);

to

//Then we find all the tests.
const context = require.context('./', true, /testing.component\.spec\.ts$/);

其他回答

为什么要这么难?

运行ng测试 打开控制台中显示的链接:

在右上角,点击Debug:

点击你想单独运行的测试:

要重新运行测试,请刷新浏览器窗口(例如使用F5)。

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

在Angular 9中,我的运气如下:

如果你想测试一个特定的文件:

ng test --test-file=path/to/your/file.component.spec.ts

如果你的Angular项目中有多个项目,并且/或正在使用NX,你可以指定一个Angular项目来测试:

ng test project-name


你也可以使用

ng test --testNamePattern componentname

例如path/to/your/component/componentname.spec.ts。这将扫描每个项目中的每个文件,并且速度较慢。


如果你只想测试自上次提交以来发生了什么变化(使用git或其他版本控制)

ng test --only-changed

不能在普通的Angular中工作。

你必须去src/test。Ts和可以更改以下行号代码18:

//Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);

to

//Then we find all the tests.
const context = require.context('./', true, /testing.component\.spec\.ts$/);

我一直在寻找答案。你的问题帮了我大忙。但是,有一点是模棱两可的。特别是,如果您执行下面的CLI命令。

npm run test -- --include src/app/component/your.component.spec.ts

它将运行单个测试文件,但在运行测试后,测试浏览器将立即关闭,由于缺少监视标志,您无法查看测试文件。因此,您必须将监视标志作为真值提供。我发现下面的CLI命令可以很好地使用watch标志。

ng test --watch=true "--include" "src/app/components/your.component.spec.ts"