ChatGPT解决这个技术问题 Extra ChatGPT

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

我是 Angular 2 的新手(以及一般的 Angular ......),我发现它非常吸引人。我正在使用 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 {
}

M
MBWise

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

您可以将其用于进一步阅读:

https://angular.io/guide/testing


谢谢,我自己也在想这个。假设我不想运行任何测试,我可以安全地删除 .spec 文件吗? (还有测试文件夹和文件,例如 e2e 文件夹?)
我也觉得这个问题需要更多的回答。我们可以完全忽略这些文件并继续我们的工作吗?
正如 awiseman 所说,规范文件确实用于测试您的应用程序。如果您不想使用测试文件,您可以简单地删除或忽略它们。您的项目将在没有规范文件的情况下继续运行。
当您使用 CLI 生成新组件时,您可以添加 --spec=false 以排除规范文件的生成。生成新组件的完整命令是:ng g component comp-name --spec=false。更多信息:github.com/angular/angular-cli/wiki/generate-component
这可以通过像这样修改 angular-cli.json 来禁用:{ "defaults": { "component": { "spec": false } } }
t
trueboroda

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

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


项目生成后可以设置这个选项吗?
@HughHughTeotl 是的,用于未来的服务生成,而不是已经生成的服务。如前所述:如果您不打算进行测试,则可以手动删除 spec.ts 文件。
P
Pritam Sinha

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


R
R15

.spec.ts 文件用于您的应用程序的 unit testing

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

ng generate component --spec=false mycomponentName