监视服务依赖项

时间:2019-02-25 22:10:07

标签: angularjs unit-testing karma-jasmine

我对监视依赖项的最佳方法感到好奇,因此可以确保在我的服务中调用了它们的方法。我减少了代码以专注于手头的问题。我可以很好地测试我的服务,但是我也想确认我的服务(在本例中为metricService)具有也被调用的方法。我知道我必须以某种方式使用createSpyObj,但是当函数正常执行时,不会捕获spyObj方法。我应该使用createSpyObj吗?还是应该使用spyObj?当涉及到依赖项时,我对间谍的概念感到困惑。

更新:使用SpyOn时,我可以看到一种方法被调用,而其他方法却没有

Test.spec

describe("Catalogs service", function() {

  beforeEach(angular.mock.module("photonServicesCommons"));

  var utilityService, metricsService, loggerService, catalogService, localStorageService;

  var $httpBackend, $q, $scope;

  beforeEach(
    inject(function(
      _catalogService_,
      _metricsService_,
      _$rootScope_,
      _$httpBackend_
    ) {
      catalogService = _catalogService_;
      $scope = _$rootScope_.$new();
      $httpBackend = _$httpBackend_;
      $httpBackend.when('GET', "/ctrl/catalog/all-apps").respond(
        {
          catalogs: catalogs2
        }
      );

      metricsService = _metricsService_;
      startScope = spyOn(metricsService, 'startScope')
      emitSuccess = spyOn(metricsService, 'emitGetCatalogSuccess').and.callThrough();
      endScope = spyOn(metricsService, 'endScope');
    })
  );



  afterEach(function(){
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
  });

  describe('get catalog', function(){
    it("Should get catalogs", function(done) {
      catalogService.normalizedDynamicAppList = testDynamicAppList1;
      catalogService.response = null;
      var promise3 = catalogService.getCatalog();
      promise3.then(function (res) {
      expect(res.catalogs).toEqual(catalogs2);
      });
      expect(metricsService.startScope).toHaveBeenCalled();
      expect(metricsService.emitGetCatalogSuccess).toHaveBeenCalled();
      expect(metricsService.endScope).toHaveBeenCalled();

      $scope.$digest();
      done();
      $httpBackend.flush();
    });
  });

});

服务

public getCatalog(): IPromise<Interfaces.CatalogsResponse> {
  if (this.response !== null) {
    let finalResponse:any = angular.copy(this.response);
    return this.$q.when(finalResponse);
  }

  return this.$q((resolve, reject) => {
    this.metricsService.startScope(Constants.Photon.METRICS_GET_CATALOG_TIME);
    this.$http.get(this.catalogEndpoint).then( (response) => {
      let data: Interfaces.CatalogsResponse = response.data;
      let catalogs = data.catalogs;
      if (typeof(catalogs)) { // truthy check
        catalogs.forEach((catalog: ICatalog) => {
          catalog.applications.forEach((application: IPhotonApplication) => {
            if( !application.appId ) {
              application.appId = this.utilityService.generateUUID();
            }
          })
        });

      } else {
        this.loggerService.error(this.TAG, "Got an empty catalog.");
      }
      this.response = data;
      this.metricsService.emitGetCatalogSuccess();
      console.log("CALLING END SCOPE");
      this.metricsService.endScope(Constants.Photon.METRICS_GET_CATALOG_TIME);
      resolve(finalResponse);
    }).catch((data) => {
      this.loggerService.error(this.TAG, "Error getting apps: " + data);
      this.response = null;
      this.metricsService.emitGetCatalogFailure();
      reject(data);
    });
  });
} // end of getCatalog()

1 个答案:

答案 0 :(得分:1)

您可以仅使用spyOn而不是使用createSpyObj。如:

beforeEach(
  inject(function(
    _catalogService_,
    _$rootScope_,
    _$httpBackend_,
    _metricsService_ //get the dependecy from the injector & then spy on it's properties
  ) {
    catalogService = _catalogService_;
    metricsService = _metricsService_; 
    $scope = _$rootScope_.$new();
    ...
    // create the spy object for easy referral later on
    someMethodSpy = jasmine.spyOn(metricsService, "someMethodIWannaSpyOn")
})
);

describe('get catalog', function(){
  it("Should get catalogs", function(done) {
    catalogService.normalizedDynamicAppList = testDynamicAppList1;
    catalogService.response = null;
    var promise3 = catalogService.getCatalog();
    ...other expects
    ...
    //do the spy-related expectations on the function spy object
    $httpBackend.flush(); // this causes the $http.get() to "move forward" 
    // and execution moves into the .then callback of the request. 
    expect(someMethodSpy).toHaveBeenCalled(); 
  });
});

我在测试复杂的角度应用程序时使用了这种模式,并将外部导入/全局依赖项包装在角度服务包装器中,以进行间谍和模拟以进行测试。

createSpyObject在这里不起作用的原因是使用它会创建一个带有指定间谍道具的全新对象metricService。它不会是与由角度注入器测试的服务中注入的“ metricService”相同。您想要从注入器获取实际的相同单例服务对象,然后监视其属性。

功能障碍的另一个来源是$httpBackend.flush()的位置。 $httpBackend是$ http服务的模拟:您可以预定义要测试的代码发出的任意数量的预期HTTP请求。然后,当您调用内部使用$ http发出对某个url的请求的函数时,$ httpBackend会拦截对$ http方法的调用(并可以执行诸如验证请求有效负载和标头,以及进行响应等操作)。 $http调用的then / error处理程序仅在测试代码调用$httpBackend.flush()之后被称为。这使您可以进行准备某种测试状态所需的任何类型的设置,然后才触发.then处理程序并继续执行异步逻辑。

对于我个人而言,每次使用$ httpBackend编写测试时,都会发生相同的事情,并且总是需要一段时间才能弄清楚或记住:)