angular2 从外部执行单元测试 class

angular2 execute unit tests from an external class

我正在做我的 angular2 测试。

我目前正在使用 ngx-translate 进行我的应用程序翻译,在进行翻译测试时,我想知道是否可以从外部帮助程序对组件执行测试 class。

现在,我正在使用 ngx-translate 的 HttpLoader,我可以毫无问题地执行我的第一个测试:

randomComponent.spec.ts

  it('should translate in english', async(() => {
    // Get the service
    translateService = TestBed.get(TranslateService);
    expect(translateService).toBeTruthy();
    checkTranslations(fixture, 'en', translateService);
  }));

  it('should translate in french', async(() => {
    // Get the service
    translateService = TestBed.get(TranslateService);
    expect(translateService).toBeTruthy();
    checkTranslations(fixture, 'fr', translateService);
  }));

translateHelper.ts

import { async, ComponentFixture } from '@angular/core/testing';
import { By } from '@angular/platform-browser';

export function checkTranslations(fixture: ComponentFixture<any>, language: string, translateService: any) {
  // Get all the content to be translated
  let contentToBeTranslated = fixture.debugElement.queryAll(By.css('*[translation]'));
  let beforeTranslationContent: string[] = [];

  contentToBeTranslated.forEach(debugElement => {
    beforeTranslationContent.push(debugElement.nativeElement.textContent);
  });

  // Test all english translations
  translateService.use(language).subscribe(() => {
    fixture.detectChanges();
    // Find missing translations
    contentToBeTranslated.forEach(debugElement => {
      expect(beforeTranslationContent.find(content => content == debugElement.nativeElement.textContent) ? true : false).toBe(false, ': Missing translation !');
    });
  });
}

到目前为止一切顺利,但如果我稍后添加语言,我将不得不为每种语言添加更多单元测试,如果我想测试我的翻译,我必须 copy/paste 所有这些测试每个组件的每种语言。


我的想法是创建一个 class 来获取当前组件 fixturetranslateService 但我如何才能将其与 beforeEach() 和所有内容联系起来?目前甚至有可能吗?

任何见解都会很有帮助。

完全有可能。我们在测试中这样做,让助手来确保测试代码的 DRY-ness 和可读性是一个很好的做法。

beforeEach() 接受一个函数,因此您唯一需要做的就是创建一个函数。

export module TestHelpers {
  export function createComponent<T>(component: Type<T>,
                                     moduleDef: TestModuleMetadata = {},
                                     afterCreationFn: ((helper: Helpers<T>) => void) = noop) {
    return async(() => {
      const fixture = TestBed
        .configureTestingModule(moduleDef)
        .createComponent(component);
      afterCreationFn(new Helpers(fixture));
      fixture.detectChanges();
    });
  }

export class Helpers<T> {
    fixture: ComponentFixture<T>;

    constructor(fixture: ComponentFixture<T>) {
      this.fixture = fixture;
    }

    component() {
      return this.fixture.componentInstance;
    }
}

}

在你的测试中

beforeEach(TestHelpers.createComponent(
    TestComponent,
    {
      imports: [],
      declarations: [
        TestComponent
      ]
    },
    (h: Helpers<TestComponent>) => {
      helper = h;
      componentInstance = helper.component();
  }));

然后您可以使用任何帮助程序函数实现帮助程序 class 来帮助您进行测试,一切都集中在一个地方