As stated in the title of the question, I am getting undefined when calling isolateScope()
. I tried to Unit Test my Angular Directive based on the instructions given on Unit Testing AngularJS Directives With External Templates.
Here is my code:
directive.js
angular.module("myTestApp")
.directive("testDirective", function(){
return{
restrict: "E",
require: "ngModel",
scope:{
ngModel: "=",
label: "@?"
},
templateUrl: "/mypath/templates/testDirective.html",
link: function($scope, element, attributes, ngModelCtrl){
$scope.functions = {},
$scope.settings = {
label: $scope.label ? $scope.label : ""
}
}
};
});
I have used karma-ng-html2js-preprocessor
for templateUrl.
karma.conf.js (Code contains only the parts that are concerned with ng-html2js)
files:[
//All Js files concerning directives are also included here...
'/mypath/templates/*.html'
],
preprocessors: {
'/mypath/templates/*.html': [ng-html2js']
},
ngHtml2JsPreprocessor: {
moduleName: 'template'
},
plugins: ['karma-*'],
directiveSpec.js
describe("testDirective Test", function(){
var scope, $compile,$httpBackend, template;
beforeEach(module('myTestApp'));
beforeEach(module('template'));
beforeEach(inject(function($rootScope, _$compile_, _$httpBackend_){
scope = $rootScope.$new();
$compile = _$compile_;
$httpBackend = _$httpBackend_;
}));
it("should check if the value of label attribute id set to dummyLabel", function(){
$httpBackend.expect('GET','/mypath/templates/testDirective.html').respond();
scope.label = 'dummyLabel';
var element = angular.element('<test-directive label= "label" ></test-directive>');
element = $compile(element)(scope);
console.log(element);
scope.$digest();
console.log('Isolate scope: '+ element.isolateScope());
expect(element.isolateScope().label).toEqual('dummyLabel');
});
});
Here the console.log(element);
prints {0: <test-directive label="label" class="ng-scope"></test-directive>, length: 1}
Problem: console.log('Isolate scope: '+ element.isolateScope());
gives undefined
.
I looked on this problem on many questions in StackOverflow but was not able to find the correct solution.
Also, I have to use the $httpBackend
to get the html file or else it throws Unexpected Request
error.
I would be really grateful for any help since I am stuck on this error since past one week!
For someone who might have the same problem:
The directive testing do not work as expected when using the $httpBackend
to mock the HTML files. It should be and it is possible to include HTML files by simply using the ng-html2js
plugin. So I removed the $httpBackend calls and used stripPrefix
to properly include my HTML files as modules. It worked!
Hope it helps someone else!