加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS指令测试失败 – 为什么“元素”具有错误的值?

发布时间:2020-12-17 17:37:39 所属栏目:安全 来源:网络整理
导读:鉴于以下指令,可以解释为什么以下测试失败? DEMO 指示 angular.module('plunker').directive('maybeLink',function($compile) { return { scope: { maybeLink: '=',maybeLinkText: '=' },link: function(scope,element,attrs) { scope.$watch('maybeLinkTex
鉴于以下指令,可以解释为什么以下测试失败? 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);
  });
});

解决方法

如果你改变了element.replaceWith(newEl);到element.append(newEl);在指令代码中,测试将通过.所以你需要的是在测试中使用额外的HTML包装器传递模板.

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读