I'm seeking assistance on how to properly test directives with replaced elements. Currently, I am encountering an issue where the compiler in Jasmine does not return the replaced element when I pass a directive element for compilation; instead, it returns the uncompiled one. Is there a correct method to test these types of directives effectively? Thank you.
Here is my code snippet:
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);
}
}
}
}]);
My testing code snippet:
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 display svg images for ads that have processed svg images", 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);
});
});
Upon console.log(element)
, instead of the object tag that should be replaced, I am getting
<svg class="ng-scope"></svg>
. Can someone shed light on why this is happening?
The directive functions correctly but I am facing challenges in testing it. Appreciate any insights. Thanks.