如何窥探Angular提供者工厂方法?

Kyl*_*Xie 3 jasmine angularjs spyon

在Jasmine中,你可以使用spyOn(object,'function').我试图窥探一个提供者,它被用作"提供者()".如何窥探呢?

提供者看起来像这样:

providers.provider('telecom', function() {
    this.$get = function() {
        return function() {
            return 'something';
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

controllers.controller('ctrl', function(telecom) {
    var isp = telecom();
});
Run Code Online (Sandbox Code Playgroud)

对于object.method(),我们可以spyOn(object,'method').那个provider()怎么样?

我用谷歌搜索,找不到任何有用的东西.我试过spyOn(提供者),但我得到错误说"undefined()方法不存在".

我甚至试图嘲笑提供者,但没有成功.(http://www.sitepoint.com/mocking-dependencies-angularjs-tests/)

tas*_*ATT 5

您可以使用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();
  });
});
Run Code Online (Sandbox Code Playgroud)

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