Get value of toggle component from HTML DOM element

Viewed 109

I have a simple component that consists of a toggle and some other elements:

<mat-slide-toggle (change)="toggle($event)" [checked]="false" attX="test"> ... </mat-slide-toggle>
<p> ... </p>

For testing, I would like to be able to know from the DOM whether the toggle is switched on or off. To do this, I created the nativeElement and use it for my tests. Everything works as expected however I'm not sure how to get the value of my toggle (true/false) using the toggleButtonElement variable.

let toggleButtonElement = fixture.nativeElement.querySelector('my-container').querySelector('mat-slide-toggle') as HTMLElement;

toggleElement.getAttribute('attX') //returns 'test' :)
toggleElement.getAttribute('checked') //returns null :(

I'm pretty new to Angular/Jasmine so forgive me if I'm missing something obvious.

1 Answers

You will need your unit test to expect a value to either be true or false.

Try this:

let toggleButtonElement = fixture.debugElement.query(
      By.css('my-container mat-slide-toggle')
    ).nativeElement;

    expect(toggleButtonElement.checked).toBeFalsy(); // default state
    toggleButtonElement.click();
    fixture.detectChanges();
    expect(toggleButtonElement.checked).toBeTruthy(); // state after click

Hope this helped.

Related