-1

When unit testing angular directives, how can I grab an instance of the directive controller and assert certain data bindings on the controller?

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() { //? }); }); }); 
1

2 Answers 2

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

    Call element.controller with $scope like element.controller($scope). Some proof of concept bellow.

    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>

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.