2017-08-02 126 views
0

我有流行情况: 模板已禁用元素取决于另一个输入元素上。测试组件 - 动态禁用功能

<input id="email" type="text" [(ngModel)]="login.username" name="username" 
<button type="button" id="login-button" [disabled]="(login.username.length < 5)"</button> 

在我的测试我检查的情况我将电子邮件数据之前,这后插入:

expect(loginButton.disabled).toBe(true); // PASS 
expect(email.value === null).toBe(false); // PASS 
console.log(email.value); // RETURN: null 

email.value = "admin"; 
email.dispatchEvent(new Event('input')); 
fixture.detectChanges(); 

console.log(email.value); // RETURN: "admin"  
expect(email.value === null).toBe(false); // PASS 
expect(loginButton.disabled).not.toBe(true); // FAILD 

为什么loginButton.disabled仍然被禁用?如果我让Chrome浏览器的控制台同它激活登录按钮后email.dispatchEvent是派:

var email = document.getElementById("email"); 
email.value = "admin"; 
email.dispatchEvent(new Event('input')); 

回答

0

最后,我找到了答案。由于Angular2 RC5发布的所有ngModel操作都是异步的,所以在测试期间我应该使用异步和whenStable()方法,如租用:

it('Test template fields', async(()=>{ 
    expect(loginButton.disabled).toBe(true); // PASS 
    expect(email.value === null).toBe(false); // PASS 
    console.log(email.value); // RETURN: null 

    fixture.whenStable().then(() => { 

     email.value = "admin"; 
     email.dispatchEvent(new Event('input')); 
     fixture.detectChanges(); 

     console.log(email.value); // RETURN: "admin"  
     expect(email.value === null).toBe(false); // PASS 
     expect(loginButton.disabled).not.toBe(true); // FAILD 

    }); 
});