2016-11-17 147 views
1

我有以下测试。它关注一个html元素,设置它的值,然后触发blur事件处理程序。模糊事件触发验证检查,如果无效应禁用保存按钮。如何等待DOM元素在Angular 2单元测试中完成渲染

当前在测试运行期间,这是失败的,但是如果我设置了一个中断点并遍历它,它将正确设置保存按钮上的disabled属性并工作。

根据我的猜测,whenStable承诺并未等待元素完成重新渲染。所以我在setTimeTimeout检查按钮状态之前等了一整秒钟,但仍然不适合我。

ComponentFixture类中是否有一个函数会等待元素在触发回调或解析承诺之前完全重新呈现?

fixture.whenStable().then(() => { 
       inputHomePhone.nativeElement.focus(); 
       setInputValue(inputHomePhone, "123"); 
       inputHomePhone.nativeElement.blur(); 
       fixture.detectChanges(); 
       return fixture.whenStable(); 
      }) 
      .then(() => { 
       setTimeout(() => { 
        expect(btnSave.classes['disabled']).toBe(true); 
        expect(btnSave.nativeElement.disabled).toBe(true); 
        debugger; 
       }, 1000) 
      }) 

这里的按钮的Html。当表单上的任何输入值无效时,它将被禁用。

<button *ngIf="!loading" 
        id="btn-save" 
        [class.disabled]="!(profileForm?.valid)" 
        class="btn primary top-space uppercase" 
        [disabled]="!(profileForm?.valid)" 
        (click)="saveChanges()"> 
       SAVE 
      </button> 

回答

0

好吧我想出了一种方法来触发对我有用的模糊。

通过nativeElement属性执行此操作会使其随机工作。我相信这是由于Angular 2正在管理DOM事件。通过改变线路

inputHomePhone.nativeElement.blur();

inputHomePhone.triggerEventHandler('blur', null);

保存按钮将立即停用,并测试现在是否已通过每一次。

我认为一般而言,您应该使用triggerEventHandler函数来测试在Angular 2中使用DOM事件。