问题描述
我有一个简单的反应形式(角 11)
<form class="searchForm" [formGroup]="form">
<input formControlName="firstName" required/>
<button [disabled]="! form.valid">Submit</button>
</form>
@Component({
selector: 'app-simple-form',templateUrl: './my-form.component.html',styleUrls: ['./my-form.component.css']
})
export class MyFormComponent {
form: FormGroup;
constructor() {
this.form = new FormGroup({
firstName: new FormControl()
});
}
}
我正在尝试做一个简单的交互测试,我正在设置一个值 在必填的文本字段中,触发输入事件。我期待 在事件 angular 运行更改检测后,将更新 按钮的禁用状态,但这不会发生。我必须触发 手动更改检测以使按钮具有正确的禁用状态。 我对这种行为有点疑惑。
it('should enable submit button',() => {
const input: HTMLInputElement = document.querySelector('input[formControlName="firstName"]');
const button: HTMLButtonElement = document.querySelector('button');
// simulate user interaction
input.focus();
input.value = 'john';
expect(component.form.valid).toBeFalse();
expect(button.disabled).toBeTruthy();
const event = new Event('input',{
bubbles: true,cancelable: true,});
input.dispatchEvent(event);
// required field has text -> form valid
expect(component.form.valid).toBeTrue();
// but button is still disabled
expect(button.disabled).toBeTrue();
fixture.detectChanges();
// only after detectChanges the disabled state is correct
expect(button.disabled).toBeFalse();
});
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)