lundi 28 décembre 2015

AngularJS / Jasmine / Karma cannot get angular.element for ng-include directive

I have a template which is loaded like so:

<li ng-repeat="favorite in favorites" ng-include="'templates/directives/favoriteContactCardDirective.html'" class="list-unit"></li>

But I cannot get its content for unit-testing. There is a standard function to achieve this:

function getCompiledElement(tag){
    var compiledElement = compile(angular.element('<div class="list-unit"></div>'))(scope);
    scope.$digest();
    return compiledElement;
  }


the whole unit-test (slightly simplified):

'use strict';
describe('Directive: FavoriteContactCardDirective', function () {
  var jasmine.getFixtures().fixturesPath = "base/test/mock/";

  var compile,
    scope,
    directiveElem;

  beforeEach(function(){
    module('feStringerApp');
    module('karmaTemplates');

    inject(function(_$compile_, _$rootScope_){
      compile = _$compile_;
      scope = _$rootScope_.$new();
      // ...  
    });
    directiveElem = getCompiledElement();
  });

  function getCompiledElement(tag){
    var compiledElement = compile(angular.element('<div class="list-unit"></div>'))(scope);
    scope.$digest();
    return compiledElement;
  }

  it('should have the right structure', inject(function(){

    expect(directiveElem).toExist();
    var accountCard = angular.element(directiveElem[0]);
    console.log('accountCard', accountCard);
  }));
});


It returns the empty block:

'accountCard', {
    0: <div class="list-unit ng-scope"></div>, 
context: <div class="list-unit ng-scope"></div>, 
length: 1
}

Before, when this template was loaded by the directive's controller, everything worked well. It looked like this:

angular.module('feStringerApp').directive('feFavoritesContactCard', function () {
  return {
    restrict: 'E',
    replace: true,
    templateUrl: 'templates/directives/favoriteContactCardDirective.html'
  };
});

But as it seems that controller does nothing except loaded the template it had been decided to get rid of it and to use ng-include instead. But now this doesn't work. So the questions are:

  1. Is it possible to make this approach (ng-include without controller) working?
  2. If yes, where the error is?

Aucun commentaire:

Enregistrer un commentaire