1

我正在使用 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功能。有什么帮助吗?

4

1 回答 1

1

您正在监视getUserJSON并返回一个值。当你这样做时,实际的函数永远不会被执行,而是被调用 spy。这就是您看不到覆盖范围的原因。

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

spyOn(service, 'getUserJSON').and.callThrough();
于 2019-09-25T08:49:09.533 回答