我有流行的情况: 模板已禁用元素取决于另一个输入元素。
<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 :(得分:0)
最后我找到了答案。由于Angular2 RC5发布所有ngModel操作都是异步的,所以在测试期间我应该使用async和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
});
});