0
votes

I'm trying to write a simple unit test case for the below functions,

  getMembers() {
    this.service.getMembers()
    .subscribe(response => {
      this.allMembers = response;
    })  
  }

Below is the specs which I've written,

 it("should call getMembers subscribe method", fakeAsync(() => {
    let membersSpy = spyOn(apiService, 'getMembers' ).and.returnValue(of(mockData));
    let subSpy = spyOn(apiService.getMembers(),'subscribe');  
    homeComponent.getMembers();
    fixture.detectChanges();
    expect(membersSpy).toHaveBeenCalledBefore(subSpy);
    expect(subSpy).toHaveBeenCalled();
  }));

  it("should call getMembers and return list of members", fakeAsync(() => {
    expect(homeComponent.allMembers).toBeDefined();
    expect(homeComponent.allMembers.length).toBeGreaterThan(1);
  }));

I'm getting the below error for this specs should call getMembers and return list of members

Expected undefined to be defined.

What I'm doing wrong here ?

1
but i'm giving an mock response to the servicestack over

1 Answers

0
votes

I would have a setup in a beforeEach and change the first test slightly.

 beforeEach(() => {
   let membersSpy = spyOn(apiService, 'getMembers' ).and.returnValue(of(mockData));
   homeComponent.getMembers();
   fixture.detectChanges();
 });

 it("should set allMembers to response of getMembers", fakeAsync(() => {
    expect(homeComponent.allMembers).toEqual(mockdata);
  }));

  it("should call getMembers and return list of members", fakeAsync(() => {
    expect(homeComponent.allMembers).toBeDefined();
    expect(homeComponent.allMembers.length).toBeGreaterThan(1);
  }));

The issue you had with the second test was that you didn't call getMembers() explicitly. Now all of this setup is in a beforeEach and the beforeEach will run before every it test.