vendredi 29 avril 2016

How to mock a service making use of $resource from within a controller?

In my controller I am making use of a service that itself uses $resource. The result of calling the service method can be either a success or error callback. My question is what is the best way to to mock these responses so I can test that the necessary stuff in my controller?

My controller:

(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;
      });
    }
  }
})();

My spec file:

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() {
      ???
    });
  });
});

Aucun commentaire:

Enregistrer un commentaire