1

I am running my first test on a directive, and while it seems that the directive is being invoked (there is a GET request being made for the directive's template url), the DOM manipulation that is supposed to occur in the link function is not - well it's that or I'm just not testing it correctly.

// Generated by CoffeeScript 1.6.3
(function() {
  var sprangularDirectives;

  sprangularDirectives = angular.module('sprangularDirectives', []);

  sprangularDirectives.directive('productDirective', function() {
    return {
      scope: {
        product: '='
      },
      templateUrl: 'partials/product/_product.html',
      link: function(scope, el, attrs) {
        return el.attr('testattr', 'isthisclasshere');
      }
    };
  });

}).call(this);

Test:

'use strict';

describe('productDirective', function() {

    var scope, el, directive, $httpBackend, compiler, compiled, html;

    beforeEach(angular.mock.module('sprangularApp'));

    beforeEach(function() {

        html = '<div data-product-directive product="currentProduct"></div>';

        inject(function($injector) {
            $httpBackend = $injector.get('$httpBackend');

            // jasmine.getHTMLFixtures().fixturesPath='base/partials/product';

            $httpBackend.when('GET', 'partials/product/_product.html').respond(
                 '  <div class="product">'
                +'      {{ currentProduct.name }}'
                +'      {{ currentProduct.page }}'
                +'  </div>'
            );

            scope = $injector.get('$rootScope');

            el = angular.element(html);

            compiler = $injector.get('$compile');
            compiled = compiler(el);
            compiled(scope);

            scope.$digest();
        });

    });

    it('Should have an isolate scope', function() {
        scope.currentProduct = {name: 'testing'};   

        console.log(el.attr('testattr'))
        console.log(el.isolateScope())
        expect(el.scope().product.name).toBe('testing');
    });
});

console.log(el.attr('testattr')) returns undefined...even though when I boot my browser up it's there. Some help would be awesome :) thanks

Melbourne2991
  • 11,707
  • 12
  • 44
  • 82

1 Answers1

0

The element you are using is the pre-compiled element reference. The element you want is returned from the "compiled(scope)" method call:

compiler = $injector.get('$compile');
compiled = compiler(el);
var element = compiled(scope);     // <-- This guy!

I use this snippet as a testing helper method:

var compileTemplate = function (scope, rawTemplate) {
    var template = angular.element(rawTemplate)
    var element = $compile(template)(scope)
    scope.$digest()
    var new_scope = element.scope()
    return [element, new_scope]
}
Harmon
  • 4,219
  • 2
  • 19
  • 16