gpt4 book ai didi

javascript - 如何测试仅用作模板的指令

转载 作者:行者123 更新时间:2023-11-30 16:59:29 24 4
gpt4 key购买 nike

我正在使用 Jasmine 来测试我的 Angular 组件。我能够很好地测试功能、服务和 Controller ,但是,我如何测试仅包含模板的指令,例如:

app.directive('myDirective', function () {
return {
restrict: 'E',
replace: true,
transclude: true,
template: '<header>' +
'<p>' +
'<a href="http://someurl1.com/home" target="_blank">Home</a>' +
'&nbsp;&nbsp;|&nbsp;&nbsp;' +
'<a href="http://someurl2.com/cookies" target="_blank">Cookies</a>' +
'&nbsp;&nbsp;|&nbsp;&nbsp;' +
'<a href="http://someurl3.com/Terms" target="_blank">Terms</a>' +
'</p>' +
'<p>Text text text text text text text text text text text text text text text text text</p>' +
'</header>'
};
});

我尝试了一些类似的方法:

 describe('Directive: header', function () {
beforeEach(module('headerDirective'));

var element, scope;

beforeEach(inject(function ($rootScope, $compile) {
element = angular.element('<header>' +
'<p>' +
'<a href="http://someurl1.com/home" target="_blank">Home</a>' +
'&nbsp;&nbsp;|&nbsp;&nbsp;' +
'<a href="http://someurl2.com/cookies" target="_blank">Cookies</a>' +
'&nbsp;&nbsp;|&nbsp;&nbsp;' +
'<a href="http://someurl3.com/Terms" target="_blank">Terms</a>' +
'</p>' +
'<p>Text text text text text text text text text text text text text text text text text</p>' +
'</header>');

scope = $rootScope;

$compile(element)(scope);
scope.$digest();
}));

it("should have the correct amount of <a>", function () {
var list = element.find('a');
expect(list.length).toBe(a);
});
});

最佳答案

您应该注入(inject)加载 Angular 应用程序模块,而不是指令。

describe('myDirective: ', function () {
var service,
scope,
compile,
element;

//load the angular app module
beforeEach(module('MyApp'));

beforeEach(inject(function ($rootScope, $compile) {
scope = $rootScope.$new();
element = angular.element('<my-directive></my-directive>');
$compile(element)(scope);
scope.$digest();
}));

it('should have 3 anchor tags', function () {
expect(element[0].querySelectorAll('a').length).toEqual(3);
});

it('should have a Home link', function () {
expect(element[0].querySelectorAll('a')[0].textContent).toEqual('Home');
});

// add more. Test for P tags.

});

JSFFIDDLE

关于javascript - 如何测试仅用作模板的指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29140698/

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