The bindToController property makes it really easy to tie a directive's isolate scope to the controller when using controllerAs. BindToConroller effectively binds the scope properties to the controller, but how can we simulate this in a unit test without having to include the directive in the test? In this post I will show an example of how to do it.
The code listing below shows a simple greeting controller that produces a greeting based on two isolate scope properties set via the markup
Controller and Directive
As you can tell, the greeting depends on fn and ln and needs them right when the controller is instantiated. Previously this created a challenge for mocking since there was no official hook to easily pass the value on behalf of the directive. Luckily for us, the Angular team has now added support for mocking this when instantiating the controller in unit tests.
The following code listing show how to pass an object to $controller(..) to supply the needed values in a Jasmine unit test:
I was really happy to see this feature added since it greatly simplifies unit testing and allows us to test controllerAs controllers in isolation from the directive.