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


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


当前回答

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

例如:

ng test foo.spec.ts

其他回答

值得一提的是,您可以通过xdescribe和xit禁用特定的测试而无需注释

xdescribe('Hello world', () => { 
  xit('says hello', () => { 
    expect(helloWorld())
        .toEqual('Hello world!');
  });
});

就像有人说过的,如果你想专注于某个测试,那么就用fdescribe和fit

fdescribe('Hello world', () => { 
  fit('says hello', () => { 
    expect(helloWorld())
        .toEqual('Hello world!');
  });
});

我发现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文档

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

例如:

ng test foo.spec.ts

在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中工作。

我一直在寻找答案。你的问题帮了我大忙。但是,有一点是模棱两可的。特别是,如果您执行下面的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"