20

我有以下情况:

控制器.js

controller('PublishersCtrl',['$scope','APIService','$timeout', function($scope,APIService,$timeout) {

    APIService.get_publisher_list().then(function(data){

            });
 }));

控制器规范.js

'use strict';

describe('controllers', function(){
    var scope, ctrl, timeout;
    beforeEach(module('controllers'));
    beforeEach(inject(function($rootScope, $controller) {
        scope = $rootScope.$new(); // this is what you missed out
        timeout = {};
        controller = $controller('PublishersCtrl', {
            $scope: scope,
            APIService: APIService,
            $timeout: timeout
        });
    }));

    it('should have scope variable equals number', function() {
      expect(scope.number).toBe(3);
    });
});

错误:

 TypeError: Object #<Object> has no method 'get_publisher_list'

我也尝试过这样的事情,但没有奏效:

describe('controllers', function(){
    var scope, ctrl, timeout,APIService;
    beforeEach(module('controllers'));

    beforeEach(module(function($provide) {
    var service = { 
        get_publisher_list: function () {
           return true;
        }
    };

    $provide.value('APIService', service);
    }));

    beforeEach(inject(function($rootScope, $controller) {
        scope = $rootScope.$new(); 
        timeout = {};
        controller = $controller('PublishersCtrl', {
            $scope: scope,
            APIService: APIService,
            $timeout: timeout
        }
        );
    }));

    it('should have scope variable equals number', function() {
      spyOn(service, 'APIService');
      scope.get_publisher_list();
      expect(scope.number).toBe(3);
    });
});

我该如何解决这个问题?有什么建议么?

4

1 回答 1

37

有两种方法(或更多肯定)。

想象一下这种服务(如果是工厂没关系):

app.service('foo', function() {
  this.fn = function() {
    return "Foo";
  };
});

使用此控制器:

app.controller('MainCtrl', function($scope, foo) {
  $scope.bar = foo.fn();
});

一种方法是使用您将使用的方法创建一个对象并监视它们:

foo = {
  fn: function() {}
};

spyOn(foo, 'fn').andReturn("Foo");

然后你将它foo作为一个 dep 传递给控制器​​。无需注入服务。那可行。

另一种方法是模拟服务并注入模拟的服务:

beforeEach(module('app', function($provide) {
  var foo = {
    fn: function() {}
  };
  
  spyOn(foo, 'fn').andReturn('Foo');
  $provide.value('foo', foo);
}));

当你注入时,foo它会注入这个。

在这里看到它:http: //plnkr.co/edit/WvUIrtqMDvy1nMtCYAfo ?p=preview

茉莉花2.0:

对于那些难以使答案起作用的人,

从 Jasmine 2.0andReturn()开始成为and.returnValue()

因此,例如在上面 plunker 的第一个测试中:

describe('controller: MainCtrl', function() {
  var ctrl, foo, $scope;

  beforeEach(module('app'));
  
  beforeEach(inject(function($rootScope, $controller) {
    foo = {
      fn: function() {}
    };
    
    spyOn(foo, 'fn').and.returnValue("Foo"); // <----------- HERE
    
    $scope = $rootScope.$new();
    
    ctrl = $controller('MainCtrl', {$scope: $scope , foo: foo });
  }));
  
  it('Should call foo fn', function() {
    expect($scope.bar).toBe('Foo');
  });

});

(来源:Rvandersteen

于 2013-12-29T21:03:13.653 回答