user3702861
user3702861

Reputation: 747

Reduce boilerplate for testing angularjs controllers

In my angular app, I have around 30 controllers and 1 test file for each of them. Those test files always begin with something like this boilerplate:

'use strict';

describe('Controller: SomeController', function ()
{
  var controller;
  var scope;
  beforeEach(function ()
  {
    module('SomeControllerModule');

    inject(function ($controller, $rootScope)
    {
      scope = $rootScope.$new();
      controller = $controller('SomeController',
        {
          $scope: scope
        });
    });
  });

  it('should prepare controller scope', function ()
  {
    console.log('scope', scope);
  });
});

Is there a way to somehow make it shorter, so that I don't have to repeat it in each of my files?

Upvotes: 1

Views: 114

Answers (2)

Mohammad
Mohammad

Reputation: 209

Yes, I have a cleaner way of doing it:

describe('HomeController', function() {

  var $scope;

  beforeEach(module('app'));

  beforeEach(inject(function($rootScope, $controller) {
    $scope = $rootScope.$new();
    $controller('HomeController', { $scope: $scope });
  }));

  it('true should be truthy', function() {
    expect(true).toBeTruthy();
  });

});

Also check out this AngularJS Scaffolding that comes with all nuts and bolts you might need in your AngularJS project.

Upvotes: 0

dshepherd
dshepherd

Reputation: 5407

There's ng-describe which looks like it could be very useful (I haven't used it personally yet). With that your code becomes something like:

ngDescribe({
    modules: 'SomeControllerModule',
    controllers: 'controller',
    tests: function (deps) {
        it('should prepare controller scope', function () {
            console.log('scope', deps.controller);
        });
    }
});

Unfortunately they don't support jasmine at the moment which probably rules it out for a lot of people.

Upvotes: 1

Related Questions