unit testing directive with isolate scope
I have created a demo project which reproduces the issue I found. Perform the following to reproduce:
$> git clone https://github.com/ajs2/angularjs-directive
$> npm install
$> bower install
$> karma start karma.conf.js
I have also tried to reproduce the issue in a jsfiddle here but there it doesn't fail.
Anyway, in that project is just one directive with one unit test file. The problem I found occurred when I implemented an isolated scope in the directive.
This is the directive:
angular.module('MyTest')
.directive('myFoo', ['$rootScope',
function ($rootScope) {
return {
restrict: 'E',
replace: true,
scope: {},
templateUrl: '/views/my-foo.html',
link: function ($scope, $element, $iAttrs, controller) {
$scope.bar = 'foo';
},
controller: function ($scope) {
$scope.foo = 'bar';
}
};
}]);
and the test I wrote tests the existence of the property 'foo' on the directive's scope as follows
var scope = $rootScope.$new(),
element = angular.element('<div><my-foo></my-foo></div>');
element = $compile(element)(scope);
scope.$digest();
expect(element.scope().foo).toEqual('bar'); // fails here
expect(element.scope().$id).not.toEqual(scope.$id); // fails too, they are the same!
Is this a bug, or is there an explanation why these karma tests fail and the jsfiddle does not ?
Same as #4640 ?
No its definitely different (thats why I created this issue)! That issue you mention is about not having a scope at all, so a test like
expect(element.scope()).toBeDefined();
would fail. This issue is about not being able to access the properties set by the directive on the scope.
After upgrade from 1.2.0-rc3 to stable 1.2.0 I'm not able to access isolated scope in my specs. Here is an example http://jsfiddle.net/lucassus/pTv49/1/ This example works fine with rc3 version.
The workaround for this issue is directiveScope = element.scope().$$childHead but it's not very elegant code.
https://github.com/angular/angular.js/commit/27e9340b3c25b512e45213b39811098d07e12e3b @lucassus
How about this: http://jsfiddle.net/pTv49/3/
@markkra thanks for your fiddle dude, that helped me figure out my issue. Basically isolateScope() doesn't work until after the $digest call.
@markkra thanks so much for this, man, I spent about 2 hours trying to figure this out today. this is the only reference i've found online to el.isolateScope().
this is the only reference i've found online to el.isolateScope().
Did you try the official API docs? =)
I did, but didn't think to look under angular.element. Google search for "isolatescope" doesn't come up with any relevant Angular API doc.
I added 'passing value from outside scope to isolated scope' which is missing on markrra's demo, check this out http://jsfiddle.net/vd1mjf0g/
Awesome! This is the second time this same issue saved my day (stupid brain)