Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS directive test fails - Why "element" has the a wrong value?

Given the following directive, could one explain why the following test fails? DEMO

DIRECTIVE

angular.module('plunker').directive('maybeLink', function($compile) {
  return {
    scope: {
      maybeLink: '=',
      maybeLinkText: '='
    },
    link: function(scope, element, attrs) {

      scope.$watch('maybeLinkText', function(newVal) {
        scope.text = newVal.replace(/\n/g, '<br>');
      });

      scope.$watch('maybeLink',function() {
        var newEl;
        if (scope.maybeLink) {
          newEl = $compile('<a href="#">{{ text }}</a>')(scope);

        } else {
          newEl = $compile('<span>{{ text }}</span>')(scope);
        } 
        element.replaceWith(newEl);
        element = newEl;
      });

    } 
  };
});

TEST

describe('Directive: maybeLink', function() {
  var scope, $compile;

  beforeEach(function() {
    module('plunker');

    inject(function($rootScope, _$compile_) {
      scope = $rootScope;
      $compile = _$compile_;
    });
  });

  function compile(html) {
    var element = $compile(html)(scope);
    scope.$digest();
    return element;
  }

  it('should create a link when link URL exists', function() {
    scope.myLinkText = 'Great Video';
    scope.myLinkURL = 'http://www.youtube.com/watch?v=rYEDA3JcQqw';

    var element = compile('<span maybe-link="myLinkURL" maybe-link-text="myLinkText"></span>');

    console.log(element[0].outerHTML); // => <span maybe-link="myLinkURL" maybe-link-text="myLinkText" class="ng-isolate-scope ng-scope"></span> 
    console.log(element.html());       // => (empty string)

    expect(element.text()).toBe('Great Video');
    expect(element.find('a').length).toBe(1);
  });
});
like image 470
Misha Moroshko Avatar asked Sep 19 '13 13:09

Misha Moroshko


1 Answers

If you change element.replaceWith(newEl); to element.append(newEl); in the directive code, the test will pass. So what you need is pass the template in the test with an additional HTML wrapper.

So just wrap the template in the test code with div or what ever valid HTML element like this, the test should pass.

var element = compile('<div><span maybe-link="myLinkURL" maybe-link-text="myLinkText"></span></div>');
like image 51
zs2020 Avatar answered Sep 27 '22 22:09

zs2020