2016-10-27 2 views
-1

Beim Testen von Winkeldirektiven: Wie kann ich eine Instanz des Directive Controllers greifen und bestimmte Datenbindungen auf dem Controller bestätigen?Instanz des Direktiven-Controllers mit Angular/Jasmine

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

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

Unit-Test

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

Ist dies nicht für Sie arbeiten? https://docs.angularjs.org/guide/unit-testing#testing-a-controller –

Antwort

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

Anruf element.controller mit $scope wie element.controller($scope). Einige Nachweise des Konzepts.

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>

Verwandte Themen