调用服务的角度单元测试

时间:2014-05-28 15:16:38

标签: angularjs unit-testing jasmine

我有一个非常简单的控制器,它有一个范围变量,可以调用服务方法来填充。我正在尝试编写测试,请确保此变量已填充,但我收到错误Expected spy find to have been called.

如何使用间谍为服务片编写此单元测试?

describe('StuffCtrl', function() {

    beforeEach(module('web'));

    var scope, ctrl, stuff;

    beforeEach(inject(function($rootScope, $controller, Stuff) {
      scope = $rootScope.$new();
      stuff = Stuff;
      ctrl = $controller('StuffCtrl', {$scope: scope, Stuff: stuff});
    }));

it('should fetch all the stuff', function() {

    // Mock the Stuff.find service
    spyOn(stuff, 'find');

    // ERROR ON THIS LINE: Expected spy find to have been called.
    expect(stuff.find).toHaveBeenCalled();
    expect(scope.stuff).toBeDefined();
  });
...

控制器

angular.module('web').controller('StuffCtrl',function($scope, $log, $routeParams, $location, Stuff){

  $scope.stuff = Stuff.find();

});

东西服务

module.factory("Stuff", ['LoopBackResource', '$injector', function(Resource, $injector) {

  var R = Resource(
      urlBase + "/stuff/:id",
      { 'id': '@id' },
      {"find": {
          url: urlBase + "/stuffs",
          method: "GET",
          isArray: true,
        }
      });


    return R;
  }]);

1 个答案:

答案 0 :(得分:2)

试试这个

describe('StuffCtrl', function() {

    beforeEach(module('web'));

    var scope, ctrl, stuff;

    beforeEach(inject(function($rootScope, $controller, Stuff) {
      scope = $rootScope.$new();
      stuff = Stuff;
      // Mock the Stuff.find service
      spyOn(stuff, 'find');
      //you're instanciating the controller here so find will get executed.
      //you need to mock find before.
      ctrl = $controller('StuffCtrl', {$scope: scope});
    }));

it('should fetch all the stuff', function() {
    expect(stuff.find).toHaveBeenCalled();
    expect(scope.stuff).toBeDefined();
  });
...