“spec.ts”文件是Angular CLI生成的用于什么目的?

288

我正在使用Angular CLI来生成和提供项目。它似乎工作得很好 - 尽管对于我的小型学习项目,它产生了更多的东西,但这是可以预料的。

我注意到它为项目中的每个Angular元素(组件、服务、管道等)生成spec.ts文件。我搜索了一下,但没有找到关于这些文件用途的解释。

这些是在使用tsc时通常隐藏的构建文件吗?我想知道,因为我想更改一个名字不太好的Component的名称,并发现该名称也被引用在这些spec.ts文件中。


import {
  beforeEach,
  beforeEachProviders,
  describe,
  expect,
  it,
  inject,
} from '@angular/core/testing';
import { ComponentFixture, TestComponentBuilder } from '@angular/compiler/testing';
import { Component } from '@angular/core';
import { By } from '@angular/platform-browser';
import { PovLevelComponent } from './pov-level.component';

describe('Component: PovLevel', () => {
  let builder: TestComponentBuilder;

  beforeEachProviders(() => [PovLevelComponent]);
  beforeEach(inject([TestComponentBuilder], function (tcb: TestComponentBuilder) {
    builder = tcb;
  }));

  it('should inject the component', inject([PovLevelComponent],
      (component: PovLevelComponent) => {
    expect(component).toBeTruthy();
  }));

  it('should create the component', inject([], () => {
    return builder.createAsync(PovLevelComponentTestController)
      .then((fixture: ComponentFixture<any>) => {
        let query = fixture.debugElement.query(By.directive(PovLevelComponent));
        expect(query).toBeTruthy();
        expect(query.componentInstance).toBeTruthy();
      });
  }));
});

@Component({
  selector: 'test',
  template: `
    <app-pov-level></app-pov-level>
  `,
  directives: [PovLevelComponent]
})
class PovLevelComponentTestController {
}
4个回答

360

规范文件是你的源代码的单元测试。在 Angular 应用程序中,约定每个 .ts 文件都有一个 .spec.ts 文件。当你使用 ng test 命令时,它们将通过 Karma 测试运行器 (https://karma-runner.github.io/) 使用 Jasmine JavaScript 测试框架进行运行。

你可以参考以下链接了解更多信息:

https://angular.io/guide/testing


23
谢谢,我自己也在想这个问题。假设我不想运行任何测试,我能安全地删除 .spec 文件吗?(以及像 e2e 文件夹这样的测试文件和文件夹?) - Kokodoko
10
我觉得这个问题需要更详细的回答。我们可以完全忽略这些文件然后继续工作吗? - cah1r
25
正如一位智者所说,规格文件确实是用于测试您的应用程序的。 如果您不想使用测试文件,可以简单地删除或忽略它们。 您的项目将在没有规格文件的情况下继续运行。 - dennismuijs
41
使用CLI生成新组件时,您可以添加 --spec=false 来排除生成规范文件。生成新组件的完整命令为:ng g component comp-name --spec=false。更多信息请查看这里:https://github.com/angular/angular-cli/wiki/generate-component。 - Dean
15
通过修改 angular-cli.json 文件可以禁用此功能,修改如下:{ "defaults": { "component": { "spec": false } } } - Ali Sherafat
显示剩余6条评论

30
如果你使用 "ng new" 命令创建一个新的 Angular 项目,你可以跳过生成 spec.ts 文件的步骤。为此,你需要使用 --skip-tests 选项。

ng new ng-app-name --skip-tests


3
项目生成后,您能否设置此选项? - HughHughTeotl
@HughHughTeotl 是的,针对未来的服务生成,而不是已经生成的服务。正如所说:如果您不打算进行测试,则可以手动删除spec.ts文件。 - arielhasidim

5

.spec.ts文件是用于单个组件的单元测试。您可以通过ng test运行Karma任务运行器。为了查看特定组件的单元测试用例的代码覆盖率,请运行ng test --code-coverage


2

.spec.ts文件用于对应用程序进行单元测试

如果您不想生成它,只需在创建新的组件时使用--spec=false。就像这样:

ng generate component --spec=false mycomponentName

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接