mardi 22 décembre 2015

Unit test Angular directive with injected service

How can I unit test this directive which makes an $http call out to MyService? How do I mock out or spy on MyService properly?

  angular.module('example')
    .directive('myDirective', ['MyService', function(MyService) {
      return {
        restrict: 'E',
        replace: true,
        templateUrl: 'templates/myDirective.html',
        scope: {
          name: '@',
          required: '='
        },
        link: function(scope, el, attrs, billingCtrl) {
          scope.data = [];

          MyService.get()
            .then(function(res) {
              scope.data = res;
            });
        }
      };
    }]);

My test:

  describe('Directive: <my-directive>', function() {
    // setup code
    beforeEach(module('example'));

    var element;
    var compile;
    var scope;
    var compiledElementScope;
    var validTemplate = '<my-directive ng-model="testModel" name="test"></my-directive>';
    var MyService = { get: function() {} };
    var $q;

    function getCompiledElement(template) {
      var compiledElement;

      compiledElement = compile(template || validTemplate)(scope);
      scope.$digest();

      return compiledElement;
    }

    beforeEach(function() {
      module(function($provide) {
        $provide.value('MyService', MyService);
      });

      inject(function($compile, $rootScope, _$q_) {
        compile = $compile;
        scope = $rootScope.$new();
        $q = _$q_;
      });

    });

    describe('my directive', function() {
      var element;

      beforeEach(function() {
        element = getCompiledElement(validTemplate);
      });

      it('should make a call to MyService and update scope.data', function() {
        // how do I asset the following
        expect(scope.data).toEqual(...);
      });
    })
  });

Aucun commentaire:

Enregistrer un commentaire