IsolateScope () gives undefined - Unit Testing directives with karma

As indicated in the title of the question, I get undefined when called isolateScope(). I tried Unit Test my Angular directive based on the instructions given in 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 used karma-ng-html2js-preprocessorfor templateUrl.

karma.conf.js (the code contains only those parts that are related to 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');
});

});

console.log(element);Prints here{0: <test-directive label="label" class="ng-scope"></test-directive>, length: 1}

Problem: console.log('Isolate scope: '+ element.isolateScope()); gives undefined.

I addressed this issue on many issues in StackOverflow, but could not find the right solution.

In addition, I have to use $httpBackendhtml to get the file, otherwise it throws an error Unexpected Request.

, !

+4
2

-, :

$httpBackend HTML. , HTML , ng-html2js. $httpBackend stripPrefix, HTML . !

, - !

0

, , ...

.respond() - . , isolateScope() undefined.

0

Source: https://habr.com/ru/post/1621108/


All Articles