Как проверить директиву data-cy? - PullRequest
0 голосов
/ 20 мая 2019

Я не знаю, как написать юнит-тест для этой директивы.Вы можете мне помочь?

import { Directive, ElementRef, Inject, Input, Renderer2 } from enter code here'@angular/core';

@Directive({
  // tslint:disable-next-line:directive-selector
  selector: '[data-cy]'
})
export class DataCyDirective {
  @Input('data-cy') dataCy: string;

  constructor(
    private el: ElementRef,
    private renderer: Renderer2,
    @Inject('production') isProd: boolean
  ) {
    if (isProd) {
      renderer.removeAttribute(el.nativeElement, 'data-cy');
    }
  }
}

1 Ответ

0 голосов
/ 21 мая 2019

Я нашел решение

 @Component({
  template: `
    <span id="expected" data-cy="elementCy"></span>
  `
})
class DataCyDirectiveTestComponent implements OnInit {
  constructor(@Inject('production') prod: boolean) {}
}

describe('DataCyDirective test version', () => {
  let component: DataCyDirectiveTestComponent;
  let fixture: ComponentFixture<DataCyDirectiveTestComponent>;

  configureTestSuite();

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [DataCyDirectiveTestComponent, DataCyDirective],
      providers: [{ provide: 'production', useValue: false }]
    }).compileComponents();
  });

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

  it('should NOT delete the data-cy attribute if production is not enabled', () => {
    const el: ElementRef<HTMLElement> = fixture.debugElement.query(By.css('#expected'));
    expect(el.nativeElement.getAttribute('data-cy')).not.toBeNull();
  });
});
...