大佬教程收集整理的这篇文章主要介绍了为什么反应式控件的更改事件不会在Jasmine Angular单元测试中触发?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
<form [formGroup]="myForm" novalidate> <input id="age" formControlName="age" (changE)="onChange()" /> <div id="ageError" *ngIf="ageIsError()"> <label>Age has errored</label> </div> </form>
零件
constructor(private fb: FormBuilder) {} ngOnInit() { this.myForm = this.fb.group({ age: [null,[Validators.min(18)]] }); } onChange() { if (this.ageIsError()) // do something } ageIsError() { return this.myForm.controls.age.hasError('min') && this.myForm.controls.age.dirty; }
单元测试
it('should show error message when age is less than 18',fakeAsync(() => { let age = component.myForm.controls.age; age.SETVALue('10',{ emitEvent: true }); fixture.detectChanges(); fixture.whenStable().then(() => { let ageError = debugElement.query(By.css('#ageError')).nativeElement; expect(component.ageIsError()).toBe(true); expect(ageError.innerText).toContain('Age has errored'); }); }));
同样,实际的实现在浏览器中工作,但单元测试失败.有没有人知道锄头在茉莉花中发出事件以将控制设置为脏状态,还是有更好的方法来实现这一点?谢谢!
作为一种解决方法,我只是使用document.createEvent(‘Event’)模拟输入事件,看起来它工作正常:
it('should show error message when age is less than 18',async(() => { const customEvent: Event = document.createEvent('Event'); customEvent.initEvent('input',false,falsE); const ageInput = fixture.debugElement.query(By.css('input#age')).nativeElement; ageInput.value = 10; ageInput.dispatchEvent(customEvent); fixture.detectChanges(); fixture.whenStable().then(() => { let ageError = fixture.debugElement.query(By.css('#ageError')).nativeElement; expect(component.ageIsError()).toBe(true); expect(ageError.innerText).toContain('Age has errored'); }); }));
我还找到了解决方案的修复程序 – 只需在detectChanges之前调用age.markAsDirty():
it('should show error message when age is less than 18',async(() => { let age = component.myForm.controls.age; age.SETVALue('10'); // { emitEvent: true } is by default age.markAsDirty(); // add this line fixture.detectChanges(); fixture.whenStable().then(() => { let ageError = fixture.debugElement.query(By.css('#ageError')).nativeElement; expect(component.ageIsError()).toBe(true); expect(ageError.innerText).toContain('Age has errored'); }); }));
我还创建了一个stackblitz example,请查看它.希望这些解决方案对您有所帮助:)
以上是大佬教程为你收集整理的为什么反应式控件的更改事件不会在Jasmine Angular单元测试中触发?全部内容,希望文章能够帮你解决为什么反应式控件的更改事件不会在Jasmine Angular单元测试中触发?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。