我正在使用 angular 6 和 jasmine 编写单元测试用例。在下面的代码函数上编写小测试用例后,我无法覆盖getUserJSON函数。如何覆盖漏洞函数以获得该函数的代码覆盖率。
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);
})
});
}
我的规范文件如下:
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();
});
});
});
我的测试用例顺利通过,但无法完全覆盖代码。我想完全涵盖getUserJSON功能。有什么帮助吗?