mrkernelpanic
mrkernelpanic

Reputation: 4451

Angular Reactive Form check if FormControl is existing in Test

I have a reactive form in Angular 5, which is working. This form has e.q. one input field and one checkbox.

<div class="form-group" *ngIf="!myForm.controls.myCheckbox.value">
    <input class="form-control" formControlName="myField"
</div>

<div class="form-group">
    <input type="checkbox" formControlName="myCheckbox">
</div>

The checkbox is used to handle the visibility of the input field: if checked input field is invisible, and vice versa.

I am writing the tests with jasmine using TestBed to configure the componentFixture.

I tried to get the formControl and check existance e.g. with following statement, but it does not work.

let myField= component.driverForm.controls['myField'];
let myCheckbox= component.driverForm.controls['myCheckbox'];
myCheckbox.setValue(true);

fixture.detectChanges();

expect(myField).toBeFalsy("myField not existing");

Expected FormControl( ... ) to be falsy 'myField not existing'.

My question is now, how can I test that the form control "myField" is visible/ invisible when clicking on the checkbox in a jasmine test?

Upvotes: 3

Views: 9786

Answers (1)

mrkernelpanic
mrkernelpanic

Reputation: 4451

OK I found myself a solution. At first I need to get the element via:

const el = fixture.debugElement.nativeElement;
let myField= el.querySelector('input[formControlName=myField]');
expect(myField).toBeTruthy();

let myCheckboxControl= component.driverForm.controls['myCheckbox'];
expect(myCheckboxControl.value).toEqual(false);
//set checkbox state to true
myCheckboxControl.setValue(true);

fixture.detectChanges();

Then I need to get the input field again after I updated the checkbox:

myField = el.querySelector('input[formControlName=myField]');
expect(myField).toBeNull("myField not existing");

Upvotes: 5

Related Questions