gpt4 book ai didi

AngularJS 指令测试失败 - 为什么 "element"有错误的值?

转载 作者:行者123 更新时间:2023-12-03 08:20:07 25 4
gpt4 key购买 nike

鉴于以下指令,可以解释为什么以下测试失败吗? 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>');

关于AngularJS 指令测试失败 - 为什么 "element"有错误的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18895738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com