What we are going to do in the next lines is sharing a small section of crAcl componet: the crGranted directive.

First at all, what can we use this for? Well, I usually use this directive to compile or not section of pages, depending on the user’s role.

.directive("crGranted", ["crAcl", "$animate", function(acl, $animate){
  return {
    restrict: "A",
    replace: false,
    transclude: "element",
    terminal: true,
    link: function(scope, elem, attr, ctrl, $transclude){
      scope.$watch(attr.crGranted, function(){
      var allowedRoles = attr.crGranted.split(",");
      if(allowedRoles.indexOf(acl.getRole()) != -1) {
        $transclude(function(clone, newScope) {
          childScope = newScope;
          clone[clone.length++] = document.createComment(" end crGranted: " + attr.crGranted + " ");
          block = {
            clone: clone
          };
          $animate.enter(clone, elem.parent(), elem);
        });
      }
      });
    }
  };
}]);

How is it possible? Simple, crGranted directive compiles and appends this HTML in your page if and only if your role is `ROLE_USER`.

<div cr-granted="ROLE_USER">Welcome user</div>

How can we test crGranted directive?

describe("crGranted directive", function() {
  var $compile,
      element,
      $scope;

  beforeEach(module("ui.router"));
  beforeEach(module("ngAnimate"));
  beforeEach(module("cr.acl"));
});

Here you have the bootstrap of Jasmine spec, that is the part of code I use to describe my feature and load `crAcl` component and its dependencies.

Each time I start a test, I first at all create a new $scope, resume a $compile component and write a base element for my tests.

Then, when the test is completed, I delete that element so that I can start every time from a clean status.

afterEach(function() {
  delete element;
});

beforeEach(inject(function(_$compile_, _$rootScope_, _crAcl_){
  $compile = _$compile_;
  $scope = _$rootScope_.$new();
  element = $compile("<div></div>")($scope);
}));

As said, the main feature of crGranted directive is allow page compiling if my role is granted.

So, here a little test I performed.

it("My role is granted", function(){
    element.append($compile("<div cr-granted="ROLE_GUEST">Ciao</div>")($scope));
    $scope.$apply();
    expect(element.html()).toContain("Ciao");
});


it("I am not granted", function(){
    element.append($compile("<div cr-granted="ROLE_USER">Ciao</div>")($scope));
    $scope.$apply();
    expect(element.html()).not.toContain("Ciao");
});

As in this case I'm not a `ROLE_USER`, I expect element not to contain `Ciao`.

Comments

comments powered by Disqus

cloudparty

Follow Us