有没有办法自动配置component.spec.ts?

Is there a way to configure component.spec.ts automatically?

我正在我的 Angular 7 应用程序中添加单元测试。 我至少有 100 个组件要测试,并且每个组件都因配置而失败:它们需要声明所需的每个依赖项。

这是我的component.spec.ts执行时的配置在哪里 ng test:

    import { async, ComponentFixture, TestBed } from 
    '@angular/core/testing';

    import { myComponent } from './mycomponent';
    import { FontAwesomeModule } from '@fortawesome/angular- 
    fontawesome';

    describe('myComponent', () => {
      let component: myComponent;
      let fixture: ComponentFixture<myComponent>;

      beforeEach(async(() => {
        TestBed.configureTestingModule({
          declarations: [ myComponent ],
          imports: [
            FontAwesomeModule
            // + Others imports
          ]
        })
        .compileComponents();
      }));

      beforeEach(() => {
        fixture = TestBed.createComponent(myComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });

      it('should create', () => {
        expect(component).toBeTruthy();
      });
    });

在某些组件中,我添加了提供程序。在某些情况下,我使用模拟服务。我所做的一切,都来自 angular docs.

有没有一种方法可以使用 Angular 轻松或自动配置单元测试(或端到端测试),而不是手动添加每个需要的模块?

我正在使用 Angular 7、jasmine (3.3.1) 和 karma (4.0.0)。

我通常单独导入所有依赖项,因为我确保测试只加载它实际需要的依赖项。但是,我找到了一种方法,可以轻松地使所有依赖项都可用于您的测试脚本,而无需单独导入每个依赖项。不是单独导入所有依赖项,而是导入声明要测试的组件的模块。通过在单元测试中导入模块,您将使所有依赖项(包括服务和组件本身)可用于测试。

我通常不厌其烦地声明依赖关系,以避免用它不会使用的代码使测试过载,理论上,这通常会使 运行 测试 运行 变慢。听起来这对你的用例来说可能没问题,因为你有很多测试要写。

除了速度上的损失外,我知道没有其他缺点,但可能会有。如果有人知道,请将它们作为评论添加到此 post。

P.S。您的 AppModule 可能正在导入依赖项。这些可能需要与组件的声明模块一起单独导入。

测试脚本

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { EasyImportComponent } from './easy-import.component';
import { EasyImportModule } from './easy-import.module';

describe('EasyImportComponent', () => {
  let component: EasyImportComponent;
  let fixture: ComponentFixture<EasyImportComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ EasyImportModule ]
        //, declarations: [ EasyImportComponent ] <-- No longer needed since module declares this already
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(EasyImportComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

我用 进行了一些研究,用 Angular 进行测试的最佳方法是什么,我找到了答案 here,有几个解决方案和很好的解释!