【问题标题】:How to test data-cy directive?如何测试 data-cy 指令?
【发布时间】:2019-10-07 00:53:43
【问题描述】:

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

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

【问题讨论】:

    标签: javascript unit-testing jestjs angular2-directives


    【解决方案1】:

    我找到了解决方案

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

    【讨论】:

      猜你喜欢
      • 2022-11-10
      • 1970-01-01
      • 2014-01-13
      • 1970-01-01
      • 2014-07-02
      • 1970-01-01
      • 1970-01-01
      • 2015-02-16
      • 2019-12-24
      相关资源
      最近更新 更多