1

I want to write test cases for mat slide toggle.

Test case

    it('should call change method on slide change', async () => {
        const nativeElement = fixture.nativeElement;
        const slider = nativeElement.querySelector('.slider');
        slider.dispatchEvent(new Event('change'));
        expect(component.toggleStatus).toHaveBeenCalled();
    
      });

My component.html

 <ng-container matColumnDef="active">
        <th mat-header-cell *matHeaderCellDef>Status</th>
        <td mat-cell *matCellDef="let row" (click)="isAction=true">
            <mat-slide-toggle class="slider" color="primary" [checked]="row.status" #toggle
                (change)="toggleStatus($event,row,toggle)">
            </mat-slide-toggle>
        </td>
    </ng-container>

Component.ts

 public toggleStatus(event: MatSlideToggleChange, service: ServiceModel, toggle: MatSlideToggle) {
        if (event.checked) {
          this.actionActivate(service, toggle);
        } else {
          this.actionDeactivate(service, toggle);
        }
      }

error when execute this test case is enter image description here

Can anyone help me to correct this test case

Lovitha
  • 7
  • 4

1 Answers1

0

For this case, I would use triggerEventHandler on the DebugElement.

it('should call change method on slide change', async () => {
        const slider = fixture.debugElement.query(By.css('.slider'));
        // Edit
        console.log(fixture.nativeElement);
        debugger;
        // make sure the slider is truthy
        expect(slider).toBeTruthy();
        slider.triggerEventHandler('change', {/* mock the event here */});
        expect(component.toggleStatus).toHaveBeenCalled();
      });

If expect(slider).toBeTruthy() fails, it means that element is not painted in the DOM.

Make sure you have the following:

import {MatSlideToggleModule} from '@angular/material/slide-toggle';
import {MatTableModule} from '@angular/material/table';

TestBed.configureTestingModule({
  imports: [MatTableModule, MatSlideToggleModule], // import is required so Angular knows how to paint
  // the elements.
});
AliF50
  • 16,947
  • 1
  • 21
  • 37
  • When I given test case as you mentioned still test is failed. const slider = fixture.debugElement.query(By.css('.slider')); it is showing null value.How to correct it. --@AliF50 – Lovitha Oct 08 '21 at 06:49
  • Check out my edit with the console.log and the debugger. If you press F12 when chrome is open and running the test, it should pause. You can then inspect the DOM to see what's going on. I am thinking the `.slider` element is not present in the DOM at that point in time. – AliF50 Oct 08 '21 at 12:38
  • You are correct. Element is not present in DOM..How can we test slider toggle ?? - AliF50 – Lovitha Oct 08 '21 at 16:42
  • I am not sure. I am thinking maybe an ngIf is blocking the element from being displayed or you're missing an impprt in the imports array. – AliF50 Oct 08 '21 at 20:49