質問のタイトルに記載されているように、 を呼び出すと 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-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
エラーがスローされます。
過去1週間からこのエラーに悩まされているので、助けていただければ本当に感謝しています!