Angular CLi生成的"spec.ts"文件是什么?

No *_*ing 172 typescript angular

我是Angular 2(和Angular一般......)的新手,我发现它非常吸引人.我正在使用Angular CLi来生成和提供项目.它似乎运作良好 - 虽然对于我的小学习项目,它产生的比我需要的多 - 但这是可以预料的.

我注意到它spec.ts为项目中的每个Angular元素生成(Component,Service,Pipe等).我一直在搜索,但没有找到这些文件的解释.

这些构建文件在使用时通常是隐藏的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 {
}
Run Code Online (Sandbox Code Playgroud)

awi*_*man 221

规范文件是源文件的单元测试.Angular应用程序的约定是为每个.ts文件提供.spec.ts文件.当您使用该ng test命令时,它们通过Karma任务运行程序使用Jasmine javascript测试框架运行.

你可以用它来进一步阅读:

https://angular.io/guide/testing

  • 使用CLI生成新组件时,可以添加`--spec = false`以排除生成spec文件.生成新组件的完整命令是:`ng g component comp-name --spec = false`.更多信息:https://github.com/angular/angular-cli/wiki/generate-component (29认同)
  • 正如awiseman所说,spec文件确实用于测试你的应用程序.如果您不想使用测试文件,只需删除或忽略它们即可.您的项目将在没有spec文件的情况下继续运行. (15认同)
  • 谢谢,我自己也在想这个.假设我不想运行任何测试,我可以安全地删除.spec文件吗?(还有测试文件夹和文件,例如e2e文件夹?) (14认同)
  • 这可以通过像这样修改`angular-cli.json`来禁用:`{"defaults":{"component":{"spec":false}}}` (9认同)
  • 我也觉得这个问题需要多一点回答.我们可以完全忽略这些文件并继续我们的工作吗? (5认同)
  • 对于 Angular 13:我无法更改 angular-cli.json 中的默认值(导致错误)并且 `--spec=false` 不起作用。*现在使用“--skip-tests”来生成没有spec.ts文件的服务。https://angular.io/cli/generate (2认同)

tru*_*oda 18

如果使用"ng new"生成新的角度项目,则可以跳过生成spec.ts文件.为此,您应该应用--skip-tests选项.

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

  • 项目生成后可以设置这个选项吗? (3认同)

小智 5

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