如何测试data-cy指令?

时间:2019-05-20 16:06:09

标签: javascript angularjs unit-testing jestjs angular2-directives

我不知道如何为该指令编写单元测试。你能帮助我吗?

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 :(得分:0)

我找到了解决方法

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