有谁能告诉我如何测试其元素被替换的指令?我面临一个问题,当我传入一个指向jasmine编译的指令元素时,编译器不会返回被替换的元素,而是返回未编译的元素。有没有适当的方法来测试这些类型的指令?感谢。
我的代码:
var svgDirective = angular.module('svgDirective', ['adFactory']);
svgDirective.directive("svg", ['$compile', '$timeout', '$http', 'ad' , function ($compile, $timeout, $http, ad) {
return {
restrict: 'EA',
link: function (scope, elem, attr) {
var refreshAd = function (id, missingFile) {
ad.notProcessed(missingFile).then(function () {
var timer = $timeout(function () {
refreshAd(id, missingFile)
}, 2000);
scope.$on("$destroy", function () {
$timeout.cancel(timer);
});
}, function () {
$http.get("/ads/" + id + ".json", {
cache: false
}).then(function (data) {
if (data["data"]["svg_image"]["url"] && missingFile.split('.').pop() === 'svg') {
elem.replaceWith("<object style='width: 75px;height:75px' data=" + data["data"]["svg_image"]["url"] + "></object>");
}
if (data["data"]["json_image"]["url"] && missingFile.split('.').pop() === 'json') {
scope.ad.json_image.url = data["data"]["json_image"]["url"];
}
});
});
};
if (scope.ad.is_svg_processed) {
elem.replaceWith("<object style='width:75px;height:75px' data=" + scope.ad.svg_image.url + "><object>");
} else {
refreshAd(attr.class, scope.ad.svg_file);
}
if (!scope.ad.is_json_processed) {
refreshAd(attr.class, scope.ad.json_file);
}
}
}
}]);
我的测试代码:
describe("svg Directive", function(){
var $compile, $scope, $templateCache, $timeout, $http, ad, element;
beforeEach(angular.mock.module("svgDirective"));
beforeEach(module("templates"));
beforeEach(inject(function(_$compile_,_$rootScope_,_$templateCache_,_$timeout_, _$http_, _ad_){
$compile = _$compile_;
$scope = _$rootScope_.$new();
$templateCache = _$templateCache_;
$timeout = _$timeout_;
$http = _$http_;
ad = _ad_;
element = '<svg></svg>'
}));
it("should show svg images for ads whose svg images are processed", function(){
$scope.ad = {is_svg_processed:true,is_json_processed:true, svg_image:{url:"https://dicerocket.s3.amazonaws.com/ad/svg_image/622/1_1398608090_28021105597015874837455612979611260004.svg"}};
element = $compile(element)($scope);
$scope.$digest();
console.log(element);
});
});
当console.log(element)
我得到<svg class="ng-scope"></svg>
而不是我想要替换的对象标记时。谁能告诉我为什么?
该指令正确运行但我似乎无法测试它。感谢。
答案 0 :(得分:4)
这里有一个类似的问题:https://stackoverflow.com/a/18898115/424783
总之,您需要将指令包装在其他元素中,如DIV
element = '<div><svg></svg></div>';