how to test the following code in jasmine - angular6

36 Views Asked by At

We have a service api layer. The angular app calls the api to get or post the required information

I have a service function which uses map and mergemap. First to post and then get the data.

I am not sure how to write the test case for that.

This is the code:

saveAndReloadData(refNo: string):Observable<DataResponseModel> {
    return this.http.post(this._remoteApiUrl + '/Savedata',this.initialdetails)
      .map((res) => {
        if(res['hasErrors']){
          console.log('Error while saving the data', res);
          return throwError(res['resultDescription']);
        } else {
          return res;
        }        
      }).catch((error: any) => this.handleError(error))
      .mergeMap((saveResp) => {
        return this.http.get(this._remoteApiUrl + '/GetDetails?refNo=' + refNo)
      })
      .map((getRes) => {
        this.FinalDetails = getRes
        return getRes;
      }).catch((error: any) => this.handleError(error)); ``` 

1

There are 1 best solutions below

3
Naren Murali On

This is how you can test it, please ask any doubts when you write for the other testing branches for this code.

desc("saveAndReloadData method", () => {
    it('should set FinalDetails', fakeAsync(() => {
        component.FinalDetails = null;
        httpServiceMock.post.and.returnValue(of({hasErrors: false}));
        httpServiceMock.get.and.returnValue(of({test: 1}));
        let output = '';
        component.saveAndReloadData.subscribe();
        flush();
        expect(component.FinalDetails).toEqual({test: 1});
    }));
});