angularjasminekarma-jasminekarma-runnerkarma-coverage

Expected spy "service method" to have been called. - Angular 10


I am writing a component unit test case in Angular but I am not sure where I am doing wrong. In earlier, I have written similar test cases but this one is eating my head.

Please check the code here:

Component Code:

ngOnInit(): void {
    this.callFavoriteProjects();
  }

  /**
   * @description To fetch all the favorites projects
   */
  public callFavoriteProjects() {
    this.loadingService.show('loading-favorites');
    this.subscriptions[this.subscriptions.length] = this.projectsFavoriteService.getAllUserFavoriteProjects()
      .subscribe((data) => {
        this.favoriteProjectsList = data;
        this.filteredProjectList = data;
        this.loadingService.hide('loading-favorites');
      },
        (error) => {
          this.toastrService.error('', 'There is an error while processing the favorite projects!', {
            timeOut: 3000,
            progressBar: true,
            progressAnimation: 'increasing',
          });
          this.loadingService.hide('loading-favorites');
        }
      );
  }

Jasmine Test case Code:

describe('FavoriteProjectsComponent', () => {
  let component: FavoriteProjectsComponent;
  let fixture: ComponentFixture<FavoriteProjectsComponent>;
  let projectsFavoriteService: ProjectsFavoriteService;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule,
        RouterTestingModule,
        MaterialModule,
        ToastrModule.forRoot()
      ],
      declarations: [ FavoriteProjectsComponent ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      providers: [
        { provide: NgxSpinnerService, useClass: NgxSpinnerServiceStub },
        { provide: ToastrService, useClass: ToastrServiceStub },
        { provide: ProjectsHelperService, useClass: ProjectsHelperServiceStub },
        { provide: ProjectsFavoriteService, useClass: ProjectsFavoriteServiceStub }
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    projectsFavoriteService = TestBed.inject(ProjectsFavoriteService);
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(FavoriteProjectsComponent);
    component = fixture.componentInstance;
    // fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });


  describe('method: ngOnInit should ', () => {
    it('call callFavoriteProjects, projectsFavoriteService.getAllUserFavoriteProjects() and return an Observable<any>', () => {
      spyOn(projectsFavoriteService, 'getAllUserFavoriteProjects').and.returnValue(observableOf([]));
      spyOn(component, 'callFavoriteProjects');
      component.ngOnInit();
      expect(component.callFavoriteProjects).toHaveBeenCalled();
      expect(projectsFavoriteService.getAllUserFavoriteProjects).toHaveBeenCalled();
    });

    it('call callFavoriteProjects, projectsFavoriteService.getAllUserFavoriteProjects() but throw Observable error', () => {
      spyOn(projectsFavoriteService, 'getAllUserFavoriteProjects').and.returnValue(throwError({ message: 'Error Message' }));
      spyOn(component, 'callFavoriteProjects');
      component.ngOnInit();
      expect(component.callFavoriteProjects).toHaveBeenCalled();
      expect(projectsFavoriteService.getAllUserFavoriteProjects).toHaveBeenCalled();
    });

  });

});

Project Favorite Stub file

import { of as observableOf } from 'rxjs';

export class ProjectsFavoriteServiceStub {

  getAllUserFavoriteProjects() {
    return observableOf([]);
  }
    
}

So, both test cases if ngOnInit is failing. I have tried fixture.detectChanges() too by putting it in beforeEach plus in every test case after calling ngOnInit().

I am not getting where it is going the wrong side. Please help. Thanks in advance.


Solution

  • The issue is spyOn(component, 'callFavoriteProjects'). When you do this, we lose implementation details about callFavoriteProjects where this method/function will just return undefined and we just know whether it was called or not. We have to write .and.callTrough to actually call this function and not just have a spy over it whether it was called or not.

    I have commented the lines that need change.

    describe('method: ngOnInit should ', () => {
        it('call callFavoriteProjects, projectsFavoriteService.getAllUserFavoriteProjects() and return an Observable<any>', () => {
          spyOn(projectsFavoriteService, 'getAllUserFavoriteProjects').and.returnValue(observableOf([]));
          spyOn(component, 'callFavoriteProjects').and.callThrough(); // change this line
          component.ngOnInit();
          expect(component.callFavoriteProjects).toHaveBeenCalled();
          expect(projectsFavoriteService.getAllUserFavoriteProjects).toHaveBeenCalled();
        });
    
        it('call callFavoriteProjects, projectsFavoriteService.getAllUserFavoriteProjects() but throw Observable error', () => {
          spyOn(projectsFavoriteService, 'getAllUserFavoriteProjects').and.returnValue(throwError({ message: 'Error Message' }));
          spyOn(component, 'callFavoriteProjects').and.callThrough(); // change this line
          component.ngOnInit();
          expect(component.callFavoriteProjects).toHaveBeenCalled();
          expect(projectsFavoriteService.getAllUserFavoriteProjects).toHaveBeenCalled();
        });
    
      });