4

質問のタイトルに記載されているように、 を呼び出すと undefined になり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-*'],

ディレクティブ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エラーがスローされます。

過去1週間からこのエラーに悩まされているので、助けていただければ本当に感謝しています!

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 に答える