Reputation: 67
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?
Upvotes: 1
Views: 2235
Reputation: 812
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();
Upvotes: 2