AngularJS 指令测试失败 - 为什么是“元素"?有错误的值吗? [英] AngularJS directive test fails - Why "element" has the a wrong value?

查看:23
本文介绍了AngularJS 指令测试失败 - 为什么是“元素"?有错误的值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下指令,能否解释为什么以下测试失败?演示

Given the following directive, could one explain why the following test fails? 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 包装器在测试中传递模板.

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.

因此,只需使用 div 或任何像这样的有效 HTML 元素将模板包装在测试代码中,测试应该通过.

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

这篇关于AngularJS 指令测试失败 - 为什么是“元素"?有错误的值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆