4

正如问题标题中所述,我在调用isolateScope(). 我尝试根据Unit Testing AngularJS Directives With External Templates上给出的说明对我的 Angular 指令进行单元测试。

这是我的代码:

指令.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-preprocessortemplateUrl。

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-*'],

指令规范.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错误。

我将非常感谢任何帮助,因为自过去一周以来我一直陷入此错误!

4

2 回答 2

0

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

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

于 2015-12-21T13:35:50.110 回答
0

对于可能有同样问题的人:

$httpBackend使用模拟 HTML 文件时,指令测试无法按预期工作。它应该是并且可以通过简单地使用ng-html2js插件来包含 HTML 文件。因此,我删除了 $httpBackend 调用,并用于stripPrefix将我的 HTML 文件正确地包含为模块。有效!

希望它可以帮助别人!

于 2015-12-22T21:16:53.433 回答