将单元测试用例写入 promise 函数时没有发生代码覆盖

Code coverage not happening while writing unit test case to the promise function

我正在使用 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 函数。有帮助吗?

您正在监视 getUserJSON 并返回一个值。当你这样做时,实际的功能永远不会执行,而是调用间谍。这就是您看不到报道的原因。

要调用实际的 getUserJSON 函数并仍然监视它​​,请将您的 spyOn 调用替换为以下代码:

spyOn(service, 'getUserJSON').and.callThrough();