我一直无法弄清楚如何在 Angular 中以反应形式测试选择下拉列表。
我按照 Angular 文档了解如何测试反应式表单,它在输入上运行良好,只需进行一些细微的调整,但我无法让它在选择时起作用。
假设我有这个选择
HTML
<div class="form-field">
<label for="contactSuffix">Suffix</label>
<select id="contactSuffix" formControlName="contactSuffix">
<option value="mr">MR</option>
<option value="mrs">MRS</option>
</select>
</div>
我正在尝试使用与输入相同的方法来测试它
it('should update the value of the contactSuffix field', () => {
const contactSuffix = fixture.nativeElement.querySelector('#contactSuffix');
contactSuffix.value = 'mr';
contactSuffix.dispatchEvent(new Event('input'));
expect(component.stepForm.controls['contactSuffix'].value).toEqual('mr');
});
我在运行测试时遇到此错误
Expected '' to equal 'mr'.
尝试触发更改事件而不是输入事件。
我会做这样的事情:
it('should update the value of the contactSuffix field', () => {
const contactSuffix = fixture.nativeElement.querySelector('#contactSuffix');
contactSuffix.value = 'mr';
contactSuffix.dispatchEvent(new Event('change'));
fixture.detectChanges(); // Trigger change detection
expect(component.stepForm.controls['contactSuffix'].value).toEqual('mr');
});