Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing angular reactive form input value without setting formcontrol

I have a form like this:

<form id="save_form" (ngSubmit)="save()">
    <input id="input_user" type="text" [formControl]="myForm" />
    <button type="submit">save</button>
</form>

I have a test like this:

const inputUser: HTMLInputElement = fixture.nativeElement.querySelector("#input_user");
const saveForm: DebugElement = fixture.debugElement.query(By.css("#save_form"));

inputUser.value = "Bob";
//component.myForm.setValue("Bob");

saveForm.triggerEventHandler("ngSubmit", null);

fixture.detectChanges();

In my component, the input value is not updating myForm. If I use the commented out syntax, the form is updated, but the input tag is not populated.

I am trying to simulate an input value from a user, is the formcontrol supposed to be updated through the input value in a test? I feel like if I just updated the formcontrol manually I am not simulating a user.

UPDATE:

    //component.searchUsers.setValue("Bob");
    const e: Event = document.createEvent("Event");
    e.initEvent("input", false, false);
    inputUser.value = "Bob";
    inputUser.dispatchEvent(e);
    fixture.detectChanges();

    myForm.triggerEventHandler("ngSubmit", null);
    fixture.detectChanges();
    fixture.whenStable().then(() => 
    expect(condition).toBe(true));
like image 631
Daniel Plainview Avatar asked May 08 '18 15:05

Daniel Plainview


1 Answers

You need to trigger change detection by dispatching a change event from the input, then detect changes. I do it as follows.

const e:Event = document.createEvent('Event');
e.initEvent('input', false, false);
inputUser.value = 'Bob';
inputUser.dispatchEvent(e);
fixture.detectChanges();
fixture.whenStable().then(() => expect(something).toEqual('something'));
like image 151
The Head Rush Avatar answered Oct 22 '22 06:10

The Head Rush