1

I am writing unit test cases by using angular 6 and jasmine. I am unable to cover the getUserJSON function after writing small test case on the below code function. How to cover hole function to get full percentage in code coverage for this function.

export class UserLoginService implements OnDestroy {



  // Store the userdata
  getUserDatafromSubject(userData: IUser) {
    this.userData.next(userData);
  }

  //To get LoggedIn User Deatils
  getUserJSON(): Promise<boolean> {
    return new Promise<boolean>((resolve) => {
      this._servSub = this.http.get<IUser>(/*environment.appBaseUrl + 'Account/LogIn' */'api/homepage/user.json').subscribe(value => {
        value.selAssetClass = 'COM';
        if (!value.userId || !value.userName || value.userAsset.length === 0 || value.pageAccess.length === 0) {
          value.isAuthorized = false;
        } else {
          value.isAuthorized = true;
        }
        this.getUserDatafromSubject(value);
        resolve(true);
      })
    });
  }

And my spec file is as follows:

import { TestBed, inject, async } from '@angular/core/testing';

import { UserLoginService } from './user-login.service';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';


describe('UserLoginService', () => {
  let service: UserLoginService;
  let httpMock: HttpTestingController;

  beforeEach(() => {

    TestBed.configureTestingModule({
      providers: [UserLoginService],
      imports: [HttpClientTestingModule],
    });

    service = TestBed.get(UserLoginService);
    httpMock = TestBed.get(HttpTestingController);
  });



  it('should call getUserJSON from apiService', function(done) {
    spyOn(service, 'getUserJSON').and.returnValue(Promise.resolve(true));
    service.getUserJSON()
      .then((result) => {     
        expect(result).toEqual(true);
        expect(service.getUserJSON).toHaveBeenCalled();             
        done();
      });
  });

});

My test case is passing fine but unable to cover code fully. I want to cover getUserJSON function fully. any help?

sai
  • 67
  • 1
  • 10
  • Why are you spying if call function in the next line? If you want to spy, spy the http call or give it proper values which should a resolve or a reject in two test cases. – Abhishek Chokra Sep 24 '19 at 14:21

1 Answers1

1

You are spying on getUserJSON and returning a value. When you do this, the actual function is never executed, instead the spy is getting called. This is why you don't see the coverage.

To call the actual getUserJSON function and still spy it, replace your spyOn call with the below code:

spyOn(service, 'getUserJSON').and.callThrough();
Johns Mathew
  • 804
  • 5
  • 6