juhi
juhi

Reputation: 578

unit testing of subscribe

I have a component which has a get call on ngOninit

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

  public setMemberRoles(): void {
    this.teamService.getMemberRoles().subscribe((response: ICreatedByRole) => {
      this.memberRoles = response;
    });
  }

I want to write test cases pf this:

it('should set member roles in variable member roles', async(() => {
    let response: ICreatedByRole[] = [];

    spyOn(teamServiceStub, 'getMemberRoles').and.returnValue(of(response));
    component.setMemberRoles();
    fixture.detectChanges();
    expect(component.memberRoles).toEqual(response);
  }));

I have tried this, but it throws error

 <spyOn> : could not find an object to spy upon for getMemberRoles()
    Usage: spyOn(<object>, <methodName>)

Any idea?

Upvotes: 0

Views: 38

Answers (1)

viveksai26
viveksai26

Reputation: 36

Mock the teamService.

class MockTeamService {

 getMemberRoles {
  return 'fake response'
   }
}

Inject this MockTeamService in providers as.

{provider: TeamService, useClass: MockTeamService}

Get the injected service.

teamService = TestBed.get(TeamService);

Then SpyOn:

const memberSpy = spyOn(teamService, 
'getMemberRoles').and.returnValue(of(response));

Upvotes: 1

Related Questions