Search code examples
angularunit-testingjasmine

Angular Unit test Cannot read properties of null


I have a slider toggle in my page and also a label text. I am writing test cases for that. But Iam getting "cannot read properties of null"

<div class="test" *ngIf="checked">
<div class="toggles">
<mat-slide-toggle [(ngModel)]="checked">Toggle1</mat-slide-toggle>
</div>
</div>

test cases

it('load slide text', ()=> {
component.checked = true;
const togtext = fixture.debugElement.nativeElement.querySelector('mat-slide-toggle') as HTMLElement;
expect(togtext.nativeElement.innerText).toContain('Toggle1');
});

Solution

  • I got the fix, when I moved my if condition to beforeeach

    beforeEach(() => {
     TestBed.configureTestingModule({
       declarations: [ParagraphComponent],
       imports: [MatSlideToggleModule, FormsModule],
    });
     fixture = 
     TestBed.createComponent(YourComponent);
     component = fixture.componentInstance;
     component.checked = true;
    
     fixture.detectChanges();
    });
    
    it('load slide text', () => {
    
    fixture.detectChanges();
    const togtext = fixture.debugElement.nativeElement.querySelector('mat-slide-toggle');
    
    expect(togtext.innerText).
    toContain('Toggle1');
    });