如何在控制器内模拟使用$ resource的服务?

时间:2016-04-29 09:45:22

标签: angularjs unit-testing jasmine

在我的控制器中,我正在使用一个本身使用$ resource的服务。调用服务方法的结果可以是成功或错误回调。我的问题是,模拟这些响应的最佳方法是什么,以便我可以在控制器中测试必要的东西?

我的控制器:

(function() {

  angular
    .module('myApp')
    .controller('widgetCtrl', widgetCtrl);

  widgetCtrl.$inject = [
    'dataService'
  ];

  function widgetCtrl(dataService) {
    var vm = this;
    vm.setAViewModelValue = setAViewModelValue;
    vm.getWidgets = getWidgets;

    function setAViewModelValue() {
      vm.blah = 'This is a simple thing to test';
    }

    function getWidgets() {
      dataService.widgets().query(function(response) {
          vm.widgets = response;
      },
      function(error) {
        vm.error = error;
      });
    }
  }
})();

我的spec文件:

describe('Controller: widgetCtrl', function() {

  beforeEach(module('myApp'));

  var widgetCtrl;
  var scope;

  var dataServiceMock = ???;

  beforeEach(inject(function($rootScope, $controller, dataService) {
    scope = $rootScope.$new();
    scope.vm = {};
    ScheduledReportCtrl = $controller('widgetCtrl as vm', {
      $scope: scope,
      dataService: dataServiceMock
    });
  }));

  describe('setAViewModelValue()', function() {
    it('sets a view model value', function() {
      scope.vm.setAViewModelValue();
      expect(scope.vm.blah).toEqual('This is a simple thing to test');
    });
  });

  describe('getWidgets()', function() {
    it('sets vm.widgets if successful', function() {
      ???
    });

    it('sets vm.error if not successful', function() {
      ???
    });
  });
});

0 个答案:

没有答案