Can anyone share experience with unit testing views? I read a lot of tutorials about how to do unit testing with views, but everything has some drawbacks.
I came along with the following approach. It works, but I'm wondering if there is a better way to do this. There are also some drawbacks, which I'll explain later on. I'm also doing E2E tests with protractor, but they are always slow, and therefore I limit them to a minimum.
This is my controller. It has two variables bound to its $scope
which are used in the view:
// test_ctrl.js angular.module('app', []) .controller('TestCtrl', ["$rootScope", "$scope", function ($rootScope, $scope) { $scope.bar = "TEST"; $scope.jobs = [ {name: "cook"} ]; }]);
The view takes the $scope.bar
into a <span>
and the $scope.jobs
array into an ng-repeat
directive:
<!-- test.html the view for this controller --> <span> Bar is {{bar || "NOT SET"}} </span> <ul> <li ng-repeat="job in jobs">{{job.name}}</li> </ul>
And this is the test:
describe('Controller: TestCtrl', function () { beforeEach(module('templates')); beforeEach(module('app')); var TestCtrl, $rootScope, $compile, createController, view, $scope; beforeEach(inject(function($controller, $templateCache, _$rootScope_, _$compile_, _$httpBackend_) { $rootScope = _$rootScope_; $scope = $rootScope.$new(); $compile = _$compile_; createController = function() { var html = $templateCache.get('views/test.html'); TestCtrl = $controller('TestCtrl', { $scope: $scope, $rootScope: $rootScope }); view = $compile(angular.element(html))($scope); $scope.$digest(); }; })); it('should test the view', function() { createController(); expect(view.find("li").length).toEqual(1) console.log($scope.jobs) }); });
In the beforeEach
function, I'll set up the controller. The createController
function (which is called from the tests itself) takes a view out of the $templateCache
, creates a controller with it's own $scope
, then it compiles the template and triggers a $digest
.
The template cache is prefilled with karmas preprocessor ng-html2js
// karma.conf.js ... preprocessors: { 'app/views/*.html': 'ng-html2js' } ...
With this approach, I have a little problem, and some questions:
1. Additional $$hashKey keys in my objects from ng-repeat
The expect($scope.jobs).toEqual([{name: "cook"}]);
in my test throws an error:
Expected [ { name : 'cook', $$hashKey : '009' } ] to equal [ { name : 'cook' } ]
I know that ng-repeat
adds these keys, but this is silly to test. The only way around I can think of is separating the controller tests and the view tests. But when I check the jobs
array inside my controller, the $$hashKey
is not present. Any ideas, why this is happening?
2. $scope problem
When I tried this for the first time, I only had my local scope defined as $scope={}
and not $scope = $rootScope.$new()
, as I have done in my other controller tests. But with just a plain object as a local scope, I wasn't able to compile it ($compile(angular.element(html))($scope);
throwed an error).
I also thought if it is a good idea to pass the $rootScope
itself as the current local scope for the controller. Is this a good approach? Or are there any drawbacks, I haven't seen yet?
3. Best practices
I would be very happy to know, how everyone else is doing unit tests in AngularJS. I think views have to be tested, because with all the angular directives, there lies a lot of logic in them, which I would be glad to see waterproofed ;)
With that being said it is generally accepted that 80% coverage is a good goal to aim for. Trying to reach a higher coverage might turn out to be costly, while not necessary producing enough benefit. The first time you run your coverage tool you might find that you have a fairly low percentage of coverage.
I think that what you're doing is a great way to unit test views. The code in your question is a good recipe for someone looking to unit test views.
Don't worry about the data. Instead, test the result of various operations, because that's what you really care about at the end of the day. So, use jasmine-jquery to verify the state of the DOM after creation of the controller, and after simulated click()
s, etc.
$rootScope
is an instance of Scope, while $rootScope.$new()
creates an instance of ChildScope. Testing with an instance of ChildScope is technically more correct because in production, controller scopes are instances of ChildScope as well.
BTW, the same goes for unit testing directives that create isolated scopes. When you $compile
your directive with an instance of ChildScope an isolated scope will be created automatically(which is an instance of Scope). You can access that isolated scope with element.isolateScope()
// decalare these variable here so we have access to them inside our tests var element, $scope, isolateScope; beforeEach(inject(function($rootScope, $compile) { var html = '<div my-directive></div>'; // this scope is an instance of ChildScope $scope = $rootScope.$new(); element = angular.element(html); $compile(element)($scope); $scope.$digest(); // this scope is an instance of Scope isolateScope = element.isolateScope(); }));
Some people say test views with Protractor. Protractor is great when you want to test the entire stack: front end to back end. However, Protractor is slow, and unit testing is fast. That's why it makes sense to test your views and directives with unit tests by mocking out any part of the application that relies on the back-end.
Directives are highly unit testable. Controllers less so. Controllers can have a lot of moving parts and this can make them more difficult to test. For this reason, I am in favor of creating directives often. The result is more modular code that's easier to test.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With