Angular Ng2-指令上的单元测试,detectChanges()不工作

Angular Ng2-指令上的单元测试,detectChanges()不工作,angular,unit-testing,directive,Angular,Unit Testing,Directive,我的指示: @Directive({ selector: '[dynamicStep]' }) export class DynamicStepDirective { @Input('dynamicStep') associatedMagnitude: number; constructor(private _renderer : Renderer2, public _el: ElementRef) {} ngOnInit() { this.setAttribute(

我的指示:

 @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');
  }));
@组件({
选择器:“dynamicStep”,
模板:“”
})
类dynamicTestComponent{
输入幅值:数字=1.00;
}
描述('DynamicStep',()=>{
设fixture=null,
组件:dynamicStatestComponent=null,
inputEl=null;
beforeach(异步(()=>{
让config:any=commonConfig;
config.declarations.push(dynamicTestComponent);
configureTestingModule(config).compileComponents();
fixture=TestBed.createComponent(dynamicTestComponent);
组件=fixture.debugElement.componentInstance;
inputEl=fixture.debugElement.query(By.css('input'));
}));
如果associatedMagnitude是一个小数点后1位的数字,则它('ngOnChanges()应使用'0.1'调用setAttribute(),异步(()=>{
component.InputMagnite=5.3;//应触发ngOnChanges()
fixture.detectChanges();
expect(inputEl.nativeElement.attributes.getNamedItem('step').value).toEqual('a');
}));

它需要a,但它得到1。我想这是因为ngOnChanges()尚未启动,或者更改尚未传播到DOM,我如何修复此问题?

您能解决此问题吗?我要花一整天的时间来解决此问题something@LppEdd嘿,很抱歉听到这个消息!不幸的是,那是很久以前的事了,我不记得了:(.祝你好运!谢谢!我终于做到了。我的问题是调用detectChanges后重新呈现模板所花的时间。使用fixture.whenStable回调并在模板内部调用expect+done成功了