Search code examples
angularunit-testingsubscribe

Angular unit testing .subscribe()


Can't unit test subscribe(). No result returned for portfolioType

component.ts

 getPortfolioType() {
    this.dataService.getPortfolioTypeList()
      .subscribe((response: any) => {
        this.portfolioType = response.payload.portfolioList;
      })
  }

data.service.ts

public getPortfolioTypeList(): any {
    return this.http.getData('/portfolio/portfolioTypeList');
  }

http.service.ts

getData(action: any, data: any = {}): any {
    const url = environment.API_URL + action;
    const params = Object.keys(data);
    let httpParams = new HttpParams();

    if (params.length) {
      params.forEach((key: string) => {
        httpParams = httpParams.append(key, data[key]);
      });
    }

    return this.http.get(url, {params: httpParams});
  }

Case for service (pass)

it('should pass service getPortfolioTypeList', () => {
    const test = {
      "test": "test"
    }
    let result: any;
    dataService.getPortfolioTypeList().subscribe(t => {
      result = t;
    });
    const req = httpMock.expectOne({
      method: "GET",
      url: environment.API_URL + '/portfolio/portfolioTypeList'
    });

    req.flush([test]);

    expect(result[0]).toEqual(test);
  });

Added a simple function call

it('Get data from getPortfolioType', () => {
    component.getPortfolioType();
    console.log(component.portfolioType); // <<< is empty
  });

Why component.portfolioType is empty?


Solution

  • I found a solution for this case

    Add a Mock for DataService

    class MockDataService {
      getPortfolioTypeList(): Observable<any> {
        return of(
          {
            "someKey": "someData"
          }
        )
      }
    }
    

    And test case

    it('Check getPortfolioType', fakeAsync(() => {
        const testResponse = {
          payload: {
            portfolioList: [
              {
                "someKey": "someData1",
              }
            ]
          }
        };
    
        spyOn(dataService, 'getPortfolioTypeList').and.returnValue(of(testResponse));
        fixture.detectChanges();
    
        component.getPortfolioType();
        tick();
        flush();
        fixture.detectChanges();
    
        expect(component.portfolioType).toBe(testResponse.payload.portfolioList);
      }));
    

    Code coverage