5

给定以下指令,有人可以解释为什么以下测试失败了吗?DEMO

指示

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;
      });

    } 
  };
});

测试

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);
  });
});
4

1 回答 1

6

如果您在指令代码中更改element.replaceWith(newEl);为,则测试将通过。element.append(newEl);因此,您需要通过额外的 HTML 包装器在测试中传递模板。

因此,只需将模板包装在测试代码中,div或者像这样有效的 HTML 元素,测试就应该通过了。

var element = compile('<div><span maybe-link="myLinkURL" maybe-link-text="myLinkText"></span></div>');
于 2013-09-19T14:56:16.090 回答