Search code examples
angularkarma-jasmineangular-test

Expecting method call from another method failing on test


Here is the function:

handleAddClinic() {
    HFSClinicTableSchema.headers.map((th) =>
        th.checked ? (th.checked = false) : th
    );
    this.popTableSchema = { ...HFSClinicTableSchema, rows: [] };
    this.openDialog(this.popupTemp);
}
openDialog(templateRef: TemplateRef<HTMLAllCollection>) {
    const dialogRef = this.dialog.open(templateRef);
    dialogRef.afterClosed().subscribe((result) => {
        console.log(`Dialog result: ${result}`, HFSClinicTableSchema);
    });
}

Here is the spec I do :

fit('should reset the page', fakeAsync(() => {
    spyOn(component, 'handleAddClinic');
    spyOn(component, 'openDialog');
    const addButton = fixture.debugElement.query(
        By.css('button#btnAddClinic')
    );
    addButton.nativeElement.click();
    tick();
    expect(component.handleAddClinic).toHaveBeenCalled(); //ok
    tick(5000);
    expect(component.openDialog).toHaveBeenCalled(); // error
}));

event though I given 5ms, my testing is failing at:

tick(5000); expect(component.openDialog).toHaveBeenCalled();

error:

 Error: Expected spy openDialog to have been called.
        at <Jasmine>

How can I resolve this?


Solution

    • You do not need fakeAsync and tick in this scenario
    • When you spy on a method the code in that method does not get called unless you use callThrough
    fit('should reset the page', () => {
      spyOn(component, 'handleAddClinic').and.callThrough();
      spyOn(component, 'openDialog');
      const addButton = fixture.debugElement.query(By.css('button#btnAddClinic'));
      addButton.nativeElement.click();
    
      expect(component.handleAddClinic).toHaveBeenCalled();
      expect(component.openDialog).toHaveBeenCalled();
    });