运行单个测试文件

Ell*_*son 99 jasmine karma-runner angular-cli angular

有没有办法运行ng test单个文件而不是整个测试套件?理想情况下,我想在编辑文件时获得最快的反馈循环,但是karma在每次保存时执行整个套件,这在构建足够大的测试套件时有点慢.

Ell*_*son 206

我发现Jasmine允许你使用(用于焦点?)前缀describeit方法f.所以,fdescribefit.如果你使用其中任何一个,业力只会运行相关的测试.因此,要聚焦当前文件,您可以采取最高级别describe并将其更改为fdescribe.适合我的目的.

  • 无法相信如此重要的功能不是更明显和直接。 (6认同)
  • 它工作但但并不理想,因为您需要更改源代码,并且最终可以在源代码管理中检入修改后的代码. (6认同)
  • 传奇回答 (5认同)
  • 请尽可能添加指向[官方文档](https://jasmine.github.io/2.1/focused_specs.html)的链接 (3认同)

Lev*_*evi 59

这可以通过include选项实现。 https://angular.io/cli/test#options

这是一个全局匹配,例如:

ng test --include='**/someFolder/*.spec.ts'
Run Code Online (Sandbox Code Playgroud)

我在8.1.0发行说明中找不到它,但@Swoox 在下面提到这是 cli 版本之后的一个功能8.1.0。感谢您弄清楚这一点。

  • 我刚刚在 CLI v9.1.0 中对此进行了测试,它运行得很好。 (3认同)
  • 也适用于 CLI v10.0.4 (2认同)

小智 26

我发现它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
Run Code Online (Sandbox Code Playgroud)

ng cli 文档

  • 不,它在 NG 9 中仍然可用。 (2认同)

DiP*_*Pix 19

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

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

正如有人已经说过,如果你想专注于一些测试,然后fdescribefit

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


Rag*_*hav 14

您可以转到src/test.ts并更改以下行:

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

const context = require.context('./', true, /**yourcomponent.component**\.spec\.ts$/);

在此处输入图片说明

  • 严格来说,这听起来像是最正确的答案,尽管大多数有关如何执行此操作的问题都通过使用 fit 和 fdescribe 解决了问题。Karma 中有一个 git 问题可以更轻松地完成此操作:https://github.com/karma-runner/karma/issues/1507。理想情况下(尽管并不简单),我们可以配置 Karma,以便对一项测试进行更改,然后只需在浏览器中单击它即可通过更新重新运行它。 (2认同)

Lui*_*mas 12

Visual Studio 代码扩展

最简单的方法是使用vscode-test-explorer扩展及其子angular-karma-test-explorerjasmine-test-adapter,如果您愿意,您将获得当前测试的列表来一一运行:

在此输入图像描述

这与我在这个问题上给出的答案相同,那里有更多细节。


2021 年 12 月更新:Angular Karma 测试资源管理器已被弃用,请考虑使用Karma 测试资源管理


Joe*_*ler 9

在 Angular 9 中,我在以下方面很幸运:

如果要测试特定文件:

ng test --test-file=path/to/your/file.component.spec.ts
Run Code Online (Sandbox Code Playgroud)

如果您只想测试自上次提交以来发生的更改(使用 git 或其他版本控制)

ng test --only-changed
Run Code Online (Sandbox Code Playgroud)

如果您的 Angular 项目中有多个项目和/或正在使用 NX,您可以指定一个 Angular 项目进行测试:

ng test project-name
Run Code Online (Sandbox Code Playgroud)

你也可以使用

ng test --testNamePattern componentname
Run Code Online (Sandbox Code Playgroud)

对于类似的东西path/to/your/component/componentname.spec.ts。这将扫描每个项目中的每个文件,并且速度较慢。


小智 5

使用 ng test --main file.spec.ts


小智 5

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

ng test --include=src\app\app.component.spec.ts
Run Code Online (Sandbox Code Playgroud)

这个对我有用!!

  • ng test --include src\app\app.component.spec.ts 也可以 (2认同)