Rishi Bharadwaj
Rishi Bharadwaj

Reputation: 2076

Test controller in Jasmine AngularJS

I am trying to test my controller and service using Jasmine.

I have a home controller defined like below

angular.module('TFPMPortal').controller('HomeController', Home);

    Home.$inject = ["$cookieStore", "PartsTrackHttpCallService", "$scope"];

    /* @ngInject */
    function Home(cookieStore, PartsTrackHttpCallService, scope) {
}

Here is my unit test using Jasmine

describe('HomeController', function () {
    var scope, ctrl, cookieStore, PartsTrackHttpService;

    beforeEach(module('TFPMPortal'));

    beforeEach(inject(function ($controller, $rootScope) {
        scope = $rootScope.$new();
        ctrl = $controller('HomeController', {
            cookieStore: null,
            partsTrackHttpService: PartsTrackHttpService,
            $scope: scope
        });
    }));

    it('should call the init data function', function () {
        var count = 0;
        PartsTrackHttpService.httpCall("common/tfpminitdata", scope.mc.PartsTrackProfile, true, true).then(function (response) {
            count = response.data.SiteList.length;
        });
        expect(scope.greeting).toBe("Greetings Frederik");
    });
});

I am getting error - 'HomeController' is not a function, got undefined.

Upvotes: 0

Views: 127

Answers (1)

Sunil D.
Sunil D.

Reputation: 18193

In each test suite (test file) you need to make sure you load the Angular module that contains the code you wish to test.

In this case, the your HomeController was declared on the module named "TFPMPortal". Load this module in your test:

beforeEach(module('TFPMPortal'));

Note that this loads the "TFPMPortal" module, but if your controller/tests are using services/factories/etc from other modules in your app, you need to load those modules too. For example, it looks like you'll need to include 'ngCookies' (b/c you use $cookieStore):

beforeEach(module('TFPMPortal', 'ngCookies'));

EDIT: Actually on further review, your test code above is fulfilling the $cookieStore dependency by passing null, so referencing the ngCookies module may not required ... on the other hand, there's no need to do this b/c Angular can inject the real $cookieStore.

Upvotes: 0

Related Questions