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

时间:2019-09-24 14:13:00

标签: angular karma-jasmine angular-unit-test

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

1 个答案:

答案 0 :(得分:0)

您正在监视getUserJSON并返回一个值。当您执行此操作时,实际函数将永远不会执行,而是会调用间谍。这就是为什么看不到覆盖范围的原因。

要调用实际的getUserJSON函数并仍然对其进行监视,请用以下代码替换您的spyOn调用:

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