Ng2 - 对Directive的单元测试,detectChanges()不起作用

时间:2017-10-17 10:19:01

标签: angular unit-testing directive

我的指示:

 @Directive({ selector: '[dynamicStep]' })
export class DynamicStepDirective {

  @Input('dynamicStep') associatedMagnitude: number;

  constructor(private _renderer : Renderer2, public _el: ElementRef) {}

  ngOnInit() {
    this.setAttribute('1');
  }

  ngOnChanges() {
    this.setAttribute('a');
  }
  setAttribute(value: string) {
    this._renderer.setAttribute(this._el.nativeElement, 'step', value);
  }

}

我的单位测试:

    @Component({
  selector: 'dynamicStep',
  template: '<input type="number" [dynamicStep]="inputMagnitude">'
})
class DynamicStepTestComponent {
  inputMagnitude: number = 1.00;
}

describe('DynamicStep', () => {
  let fixture = null,
    component: DynamicStepTestComponent = null,
    inputEl = null;
  beforeEach(async(() => {
    let config: any = commonConfig;
    config.declarations.push(DynamicStepTestComponent);
    TestBed.configureTestingModule(config).compileComponents();
    fixture = TestBed.createComponent(DynamicStepTestComponent);
    component = fixture.debugElement.componentInstance;
    inputEl = fixture.debugElement.query(By.css('input'));
  }));

  it('ngOnChanges() should call setAttribute() with \'0.1\' if associatedMagnitude is a number with 1 decimal place', async(() => {
    component.inputMagnitude = 5.3; //should trigger ngOnChanges()
    fixture.detectChanges();
    expect(inputEl.nativeElement.attributes.getNamedItem('step').value).toEqual('a');
  }));

它预计会得到1.但我认为这是因为ngOnChanges()没有触发,或者更改尚未传播到DOM,我该如何解决?

0 个答案:

没有答案