Unit Testing Directive Scope

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 10 years ago
Updated 5 years ago

Unit test your AngularJS directives that make changes to $scope as well as their own isolated scopes.

John Lindquist: If I want to test the scope of the directive I can do something like, "Should respond to a click." And then when I click on the element I'm going to use a browser trigger utility which is actually shipped within Angular JS source code so I'll say "Click."

Once I trigger that, I expect the scope clicked to be true. This scope is simply the scope that I injected into the element and I can just expect it to be true if I say, "Element bind click," and then, "Scope click is true." This should pass justifying because that's the scope I injected and that's the same as the scope that's being set here.

Now where you may run into a problem is if you isolate the scope. So say, for example, we'll return a link function here using the directive descriptors. And then we'll isolate the scope and you can see that our tests are going to start failing because our scope is isolated. We'll get more into testing those later but you just need to realize that you can no longer test the injected scope.

You have to get the scope off of the element using this syntax, "Element.scope," and then check the property on that because this is the scope that the directive created for it, the isolated scope instead of the scope that you injected.

Big difference. Very important to know.

Marian Zburlea
Marian Zburlea
~ 8 years ago

I've used isolateScope() to work: expect(element.isolateScope().clicked).toBeTruthy();

Markdown supported.
Become a member to join the discussionEnroll Today