0

I am trying to gain code coverage on my component by implementing a unit test in my spec file, as follows:

home.component.spec.ts

import { HomeService } from './home.service';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';

import { HomeComponent } from './home.component';
import { of } from 'rxjs';

describe('HomeComponent', () => {
  let component: HomeComponent;
  let fixture: ComponentFixture<HomeComponent>;

  // stubs
  const registryStub: HomeComponent = jasmine.createSpyObj('HomeComponent', ['getUserData']);
  const fakeNames = {x: 1};

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      declarations: [HomeComponent]
    })
      .compileComponents();
  });

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

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


  it('should navigate on promise - success', fakeAsync(() => {

    spyOn(component, 'getUserData').and.returnValue(of(fakeNames));
    (registryStub.getUserData as jasmine.Spy).and.returnValue(Promise.resolve(['test']));
    component.getUserData();

    tick();
    expect(component.getUserData).toHaveBeenCalled();



    // spyOn(component, 'getUserData').and.returnValue(of(fakeNames));
    // component.getUserData().toPromise()
    // .then((data: any) => {
    //   expect(data).toEqual(fakeNames);
    // });




  }));


});

When I run the "ng test --code-coverage" command, I check that the code gap inside the "then" and "catch" blocks are not being covered, as you might see in the illustration below:

code coverage is not being conquered within the red colored area

Could anyone point me to the right direction in order to have a complete code coverage on this component?

By the way, I have a public repo for this.

New contributor
user274378 is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

Browse other questions tagged or ask your own question.