admin管理员组

文章数量:1194922

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 ;)

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 ;)

Share Improve this question edited Jul 22, 2016 at 10:17 w00t 18.3k8 gold badges56 silver badges62 bronze badges asked Apr 15, 2014 at 12:23 23tux23tux 14.7k16 gold badges96 silver badges194 bronze badges 2
  • It might be worth noting that using the track by expression in the ng-repeat directive might help you get rid of the hashkeys (and speed up your lookups). See codelord.net/2014/04/15/… – titusn Commented Apr 29, 2015 at 13:26
  • 2 This has nothing to do with unit testing, but after looking at the sample controller I want to leave this comment here for the erudition of the passing programmer: its a good practice to not pollute the $scope with controller's local variables. Better use this.bar = "TEST", and reference it in the view with ng-controller="TestCtrl as ctrl" and ctrl.bar. – jrharshath Commented Dec 8, 2015 at 20:44
Add a comment  | 

1 Answer 1

Reset to default 25

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.


1. ng-repeat $$hashKey

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.


2. $scope = $rootScope.$new() ain't no problem

$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(); 
}));

3. +1 Testing Views

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.

本文标签: javascriptUnit test viewsbest practiceStack Overflow