我知道你可以像这样加载、编译和测试一个Angular指令:
it('Replaces the element with the appropriate content', function () {
var element = $compile("<my-directive></my-directive>")($rootScope);
$rootScope.$digest();
expect(element).toContain("some HTML...");
});
是否有一种方法来做完全相同的,但加载和编译一个HTML片段(从一个文件),而不是创建一个指令?这个片段只是一个ngRepeat和一个ngController——把它包装成一个指令只是增加了一层不必要的复杂性,但我仍然希望能够测试生成的HTML。
例如,对于HTML部分' my-table.html':
<table class="table table-condensed table-striped" data-ng-controller="MyController">
<tbody>
<tr data-ng-repeat="item in myItems">
...
我将有一个Jasmine测试,看起来像:
it('Replaces the element with the appropriate content', function () {
var element = $compile("my-table.html")($rootScope);
$rootScope.$digest();
expect(element).toContain("some HTML...");
});
我不认为你应该只测试指令的模板,因为指令是在你的代码中使用的,而不是模板本身。
然而,我认为你应该做$http.get('my-table.html')
,将内容转换为变量并编译。
var template;
beforeEach(inject(function($http, $httpBackend){
$http.get('my-table.html').then(function(data) {
template = data;
});
$httpBackend.flush();
}));
it('Replaces the element with the appropriate content', function () {
var element = $compile(template)($rootScope);
$rootScope.$digest();
expect(element).toContain("some HTML...");
});
这只是它应该如何工作的一个想法。不确定这是否真的有效-还没有测试过,但如果我需要的话,我会这样做。