2

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?

1 Answer 1

7

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/

Sign up to request clarification or add additional context in comments.

1 Comment

and you should make sure that the source code of the needed controllers are loaded in your karma config in the "files" section. The name of the module that you load in the beforeEach(module('modulename')); command in the test itself must match the module name that you use in your controller source file e.g. angular.module('modulename', []).controller...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.