2016-10-27 4 views
-1

ユニットのアンギュラディレクティブをテストする場合、ディレクティブコントローラのインスタンスを取得し、コントローラ上の特定のデータバインディングをアサートするにはどうすればよいですか? element.controller($scope)よう$scope角型/ジャスミン型のディレクティブコントローラのインスタンスを取得

function myDirective() { 
    return { 
    restrict: 'E', 
    replace: true, 
    templateUrl: 'tpl.html', 
    scope: { }, 
    controller: function($scope) { 
     $scope.text = 'Some text'; 
    } 
    }; 
} 

angular 
    .module('example') 
    .directive('myDirective', [ 
    myDirective 
    ]); 

ユニットテスト

describe('<my-directive>', function() { 
     var element; 
     var $compile; 
     var $scope; 

     beforeEach(module('example')); 

     beforeEach(function() { 
     inject(function(_$compile_, _$rootScope_) { 
      $compile = _$compile_; 
      $scope = _$rootScope_.$new(); 
     }); 
     }); 

     describe('basic functionality', function() { 
     beforeEach(function() { 
      element = $compile('<my-directive></my-directive')($scope); 
      $scope.$digest(); 
     }); 

     it('should bind the correct text', function() { 
      //? 
     }); 
     }); 
    }); 
+0

これはあなたのために動作しませんか? https://docs.angularjs.org/guide/unit-testing#testing-a-controller –

答えて

0
element = $compile('<my-directive></my-directive')($scope); 
$scope.$digest(); 
ctrl = element.controller('myDirective'); 
0

コールelement.controller。ある種の実証証明。

angular 
 
    .module('example', []) 
 
    .directive('myDirective', [ 
 
    function myDirective() { 
 
     return { 
 
     restrict: 'E', 
 
     replace: true, 
 
     //template: ['<div>{{ text }}</div>'].join(''), 
 
     scope: {}, 
 
     controller: function($scope) { 
 
      $scope.text = 'Some text'; 
 
     } 
 
     }; 
 
    } 
 
    ]); 
 

 
describe('<my-directive>', function() { 
 
    var element; 
 
    var $compile; 
 
    var $scope; 
 

 
    beforeEach(module('example')); 
 

 
    beforeEach(function() { 
 
    inject(function(_$compile_, _$rootScope_) { 
 
     $compile = _$compile_; 
 
     $scope = _$rootScope_.$new(); 
 
    }); 
 
    }); 
 

 
    describe('basic functionality', function() { 
 
    beforeEach(function() { 
 
     element = $compile('<my-directive></my-directive')($scope); 
 
     $scope.$digest(); 
 
    }); 
 

 
    it('should bind the correct text', function() { 
 
     expect(element.controller($scope).scope().$$childTail.text).toEqual('Some text') 
 
    }); 
 
    }); 
 
});
<link href="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine.css" rel="stylesheet" /> 
 
<script src="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine-2.0.3-concated.js"></script> 
 
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-mocks.js"></script>

関連する問題