I have been unable to figure out how to test a select dropdown in a reactive form in Angular.
I followed the Angular documentation for how to test reactive forms and it works fine on inputs with some minor tweaking, but I can't get it to function for a select.
Say I have this select
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>
And I am trying to test it using the same method that works for inputs
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');
});
I am getting this error running the test
Expected '' to equal 'mr'.
Try triggering change event instead of the input event.
I'd do something like this:
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');
});