有没有一种方法可以自动配置component.spec.ts?

时间:2019-02-15 20:29:15

标签: angular angular-test angular-testing

我正在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,茉莉(3.3.1)和业力(4.0.0)。

2 个答案:

答案 0 :(得分:1)

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

我通常会麻烦地声明依赖项,以避免用它不会使用的代码使测试过载,从理论上讲,这通常会使运行测试的运行速度变慢。听起来这可能适合您的用例,因为您要编写许多测试。

除了速度下降之外,我没有其他缺点,但可能还有其他缺点。如果有人知道的话,请将其添加为这篇文章的评论。

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();
  });
});

答案 1 :(得分:0)

我已经用什么是使用Angular进行测试的最佳方法进行了一些研究,并且找到了答案here,其中包含几种解决方案和详尽的解释!