角度单元测试控制器 - 控制器内的模拟服务

时间:2013-12-29 17:43:25

标签: unit-testing angularjs karma-runner karma-jasmine

我有以下情况:

controller.js

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

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

            });
 }));

controllerSpec.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);
    });
});

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

1 个答案:

答案 0 :(得分: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

Jasmine 2.0:

对于那些努力使答案有效的人,

自Jasmine 2.0 andReturn()成为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