【问题标题】:How to spyOn Angular provider factory method?如何窥探 Angular 提供者工厂方法?
【发布时间】:2015-03-04 14:54:12
【问题描述】:

在 Jasmine 中,您可以 spyOn(object, 'function')。 我正在尝试监视一个提供程序,该提供程序用作“提供程序()”。 如何窥探它?

提供者如下所示:

providers.provider('telecom', function() {
    this.$get = function() {
        return function() {
            return 'something';
        }
    }
}

在控制器中,它会这样使用:

controllers.controller('ctrl', function(telecom) {
    var isp = telecom();
});

对于 object.method(),我们可以 spyOn(object, 'method')。 provider() 呢?

我用谷歌搜索过,找不到任何有用的东西。 我尝试了 spyOn(provider),但出现错误提示“undefined() 方法不存在”。

我什至尝试模拟提供者,但没有成功。 (http://www.sitepoint.com/mocking-dependencies-angularjs-tests/)

【问题讨论】:

    标签: angularjs jasmine spyon


    【解决方案1】:

    你可以使用createSpy:

    describe('Describe', function() {
    
      var $scope, createController;
    
      var telecomSpy = jasmine.createSpy('telecomSpy');
    
      beforeEach(module('myApp'));
    
      beforeEach(inject(function($rootScope, $controller) {
    
        $scope = $rootScope.$new();
    
        createController = function() {
          $controller('MyController', {
            $scope: $scope,
            telecom: telecomSpy
          });
        };
      }));
    
      it('It', function() {
    
        expect(telecomSpy).not.toHaveBeenCalled();
    
        createController();
    
        expect(telecomSpy).toHaveBeenCalled();
      });
    });
    

    演示: http://plnkr.co/edit/bdGZtOKV9mewQt9hteDo?p=preview

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-15
      • 2020-04-07
      • 2014-03-03
      • 2018-10-20
      相关资源
      最近更新 更多