Peter Pan
Peter Pan

Reputation: 249

Jasmine + karma + angular test create controller

Where I make mistake? How can I get instance of controller in Jasmine + angular? How can I resolve controller? I have no idea what should I use to resolve that.

'use strict';

angular.module('myApp.contact', ['ui.router'])
.controller('contactCtrl', ['$scope', function ($scope) {
    $scope.contact = {
        name: 'John Doe'
    };
}]);


describe('myApp.contact module tests', function () {
    var scope, createController;

    beforeEach(inject(function ($rootScope, $controller) {
        scope = $rootScope.$new();

        createController = function () {
            return $controller('contactCtrl', {
                '$scope': scope
            });
        };
    }));

    it('contact name is John Doe', function () {
        var controller = createController();
        expect(controller).toEqual('John Doe');
    });
});

myApp.contact module tests
    ✗ contact name is John Doe
        Error: [ng:areq] Argument 'contactCtrl' is not a function, got undefined
        http://errors.angularjs.org/1.4.9/ng/areq?p0=contactCtrl&p1=not%20a%20function%2C%20got%20undefined
            at E:/angular-seed/app/bower_components/angular/angular.js:68:12
            at assertArg (E:/angular-seed/app/bower_components/angular/angular.js:1816:11)
            at assertArgFn (E:/angular-seed/app/bower_components/angular/angular.js:1826:3)

Upvotes: 1

Views: 893

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

You had missed several things here

  1. You need to initialize angular module to make your controller & all other components available by doing module('myApp.contact') in your before each so that Error: [ng:areq] Argument 'contactCtrl' is not a function, got undefined will went away.
  2. Then inside your Assert statement of test you should use scope object instead of controller(you could use controller when your properties are bounded to this)
  3. Don't forget to refer contactCtrl.js & ui-router.js on page.

    expect(scope.contact.name).toEqual('John Doe');
    

Code

describe('myApp.contact module tests', function () {
    var scope, createController;
    beforeEach(module('myApp.contact')); //1st change

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

    it('contact name is John Doe', function () {
        var controller = createController();
        expect(scope.contact.name).toEqual('John Doe'); //2nd change
    });
});

Upvotes: 2

Related Questions