camcam
camcam

Reputation: 2627

TypeError: $controller is not a function - angularjs with jasmine

I am trying to set up a test for AngularJS app using Jasmine. It follows the docs but is a bit simpler. The fiddle has the following code:

angular.module('myapp', [])
  .controller('MyCtrl', ['$scope', function MyCtrl($scope) {
    $scope.greeting = "hello";
  }]);

describe('My controller', function() {
  var $controller;
  module('myapp');
  inject(function(_$controller_) {
    $controller = _$controller_;

  });

  it('greets', function() {
    var $scope = {};
    var controller = $controller('MyCtrl', {
      $scope: $scope
    });
    expect($scope.greeting).toEqual('hello');
  })

});

And Jasmine reports an error: TypeError: $controller is not a function.

How to correct the code to get rid of this error and be able to test the controller?

Upvotes: 2

Views: 5936

Answers (1)

dfsq
dfsq

Reputation: 193301

You need to instantiate the app module and inject $controller for each test using beforeEach blocks:

describe('My controller', function() {
    var $controller;

    beforeEach(module('myapp'));

    beforeEach(inject(function(_$controller_) {
        $controller = _$controller_;
    }));

    it('greets', function() {
        var $scope = {};
        var controller = $controller('MyCtrl', {
            $scope: $scope
        });
        expect($scope.greeting).toEqual('hello');
    })

});

Demo: https://jsfiddle.net/f5ebb55f/6/

Upvotes: 7

Related Questions