Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit-testing directive controllers in Angular without making controller global

In Vojta Jina's excellent repository where he demonstrates testing of directives, he defines the directive controller outside of the module wrapper. See here: https://github.com/vojtajina/ng-directive-testing/blob/master/js/tabs.js

Isn't that bad practice and pollute the global namespace?

If one were to have another place where it might be logical to call something TabsController, wouldn't that break stuff?

The tests for the mentioned directive is to be found here: https://github.com/vojtajina/ng-directive-testing/commit/test-controller

Is it possible to test directive controllers separate from the rest of the directive, without placing the controller in a global namespace?

It would be nice to encapsulate the whole directive within the app.directive(...) definition.

like image 989
Kenneth Lynne Avatar asked Mar 09 '13 18:03

Kenneth Lynne


People also ask

Which directive is used for controller in Angular?

AngularJS ng-controller Directive The ng-controller directive adds a controller to your application. In the controller you can write code, and make functions and variables, which will be parts of an object, available inside the current HTML element. In AngularJS this object is called a scope.

Do we write unit test for controller?

We can write an unit test for this controller method by following steps: Create the test data which is returned when our service method is called. We use a concept called test data builder when we are creating the test data for our test.

What is the difference between AngularJS directives and controllers?

A controller is usually used to contain and maintain the logic for your view, which gets bound to your view via $scope. A directive is something that you might use repeatedly and is called in your view directly through the directive name which you can pass in as an attribute.

Which one is the test entry file for the unit test?

The angular-cli configuration of karma uses the file “test. ts” as the entry point of the tests for the application.


3 Answers

I prefer at times to include my controller along with the directive so I need a way to test that.

First the directive

angular.module('myApp', [])
  .directive('myDirective', function() {
    return {
      restrict: 'EA',
      scope: {},
      controller: function ($scope) {
        $scope.isInitialized = true
      },
      template: '<div>{{isInitialized}}</div>'
    }
})

Then the tests:

describe("myDirective", function() {
  var el, scope, controller;

  beforeEach inject(function($compile, $rootScope) {
    # Instantiate directive.
    # gotacha: Controller and link functions will execute.
    el = angular.element("<my-directive></my-directive>")
    $compile(el)($rootScope.$new())
    $rootScope.$digest()

    # Grab controller instance
    controller = el.controller("myDirective")

    # Grab scope. Depends on type of scope.
    # See angular.element documentation.
    scope = el.isolateScope() || el.scope()
  })

  it("should do something to the scope", function() {
    expect(scope.isInitialized).toBeDefined()
  })
})

See angular.element documentation for more ways to get data from an instantiated directive.

Beware that instantiating the directive implies that the controller and all link functions will already have run, so that might affect your tests.

like image 103
James van Dyke Avatar answered Oct 11 '22 20:10

James van Dyke


Excellent question!

So, this is a common concern, not only with controllers but also potentially with services that a directive might need to perform its job but don't necessarily want to expose this controller / service to the "external world".

I strongly believe that global data are evil and should be avoided and this applies to directive controllers as well. If we take this assumption we can take several different approaches to define those controllers "locally". While doing so we need to keep in mind that a controller should be still "easily" accessible to unit tests so we can't simply hide it into directive's closure. IMO possibilities are:

1) Firstly, we could simply define directive's controller on a module level, ex::

angular.module('ui.bootstrap.tabs', [])
  .controller('TabsController', ['$scope', '$element', function($scope, $element) {
    ...
  }])
 .directive('tabs', function() {
  return {
    restrict: 'EA',
    transclude: true,
    scope: {},
    controller: 'TabsController',
    templateUrl: 'template/tabs/tabs.html',
    replace: true
  };
})

This is a simple technique that we are using in https://github.com/angular-ui/bootstrap/blob/master/src/tabs/tabs.js which is based on Vojta's work.

While this is a very simple technique it should be noted that a controller is still exposed to the whole application which means that other module could potentially override it. In this sense it makes a controller local to AngularJS application (so not polluting a global window scope) but it also global to all AngularJS modules.

2) Use a closure scope and special files setup for testing.

If we want to completely hide a controller function we can wrap code in a closure. This is a technique that AngularJS is using. For example, looking at the NgModelController we can see that it is defined as a "global" function in its own files (and thus easily accessible for testing) but the whole file is wrapped in closure during the build time:

  • https://github.com/angular/angular.js/blob/master/src/angular.prefix
  • https://github.com/angular/angular.js/blob/master/src/angular.suffix

To sum up: the option (2) is "safer" but requires a bit of up-front setup for the build.

like image 58
pkozlowski.opensource Avatar answered Oct 11 '22 20:10

pkozlowski.opensource


James's method works for me. One small twist is though, when you have an external template, you would have to call $httpBackend.flush() before $rootScope.$digest() in order to let angular execute your controller.

I guess this should not be an issue, if you are using https://github.com/karma-runner/karma-ng-html2js-preprocessor

like image 10
buddyspike28 Avatar answered Oct 11 '22 21:10

buddyspike28