如问题标题所述,调用isolateScope()时我变得不确定。我尝试根据Unit Testing AngularJS Directives With External Templates上的说明对我的Angular指令进行单元测试。

这是我的代码:

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 : ""
        }
      }
    };
  });

我已经将karma-ng-html2js-preprocessor用于templateUrl。

karma.conf.js (代码仅包含与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-*'],

指令Spec.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);打印{0: <test-directive label="label" class="ng-scope"></test-directive>, length: 1}
问题: console.log('Isolate scope: '+ element.isolateScope());提供了undefined

我在StackOverflow中的许多问题上都看过这个问题,但找不到正确的解决方案。

另外,我必须使用$httpBackend来获取html文件,否则它将引发Unexpected Request错误。

我非常感谢您的帮助,因为自从过去一个星期以来我一直坚持这个错误!

最佳答案

乍一看这里只是一个猜测,但是...

您的.respond()需要返回一些内容。现在,您正在拦截对模板的请求,并且没有任何响应,从而导致未定义空数据和isolateScope()

10-05 21:16