DoomVroom
DoomVroom

Reputation: 327

How to Unit Test Angular with Jasmine Controller inside a Directive

So I am trying to learn how to unit test with Jasmine with Angular. I have got a number of unit tests working but this one has stumped me. I took out the alerts array in my test you can make it any array.. But how to mock this and getting this to work has really stumped me. I would think that the object would exist.

(function () {
var app = angular.module("TabDirectives", ["Communication"]);

app.directive("sentAlerts", ["DirectiveProvider", "DataProvider", function (DirectiveProvider, DataProvider) {
    var dir = DirectiveProvider("SentAlerts");
    dir.controller = function () {
        var ctrl = this;

       DataProvider("AlertsByDate").then(function (Result) {
            ctrl.AlertList = Result.data;
        });
    };
    dir.controllerAs = "Alerts"
    return dir;
}]);
})()

I have a test that looks like

describe("Tab Directive Unit Tests", function () {

var controller;

describe("Tab Directive Default Values", function () {

    beforeEach(inject(function ($rootScope, $compile) {
        element = angular.element("<sent-alerts></sent-alerts>");
        $compile(element)($rootScope.$new());
        $rootScope.$digest();
        controller = element.controller;
    }));

    it("Ctrl should be this", function () {
        expect(controller.ctrl).toBe(controller.this);
    });

    it("AlertList should have Alerts", function () {
        expect(controller.ctrl.AlertList).toBe(alerts);
    });

});

});

The error I'm getting looks like

TypeError: Cannot read property 'AlertList' of undefined

Upvotes: 1

Views: 638

Answers (1)

alcfeoh
alcfeoh

Reputation: 2267

You have to initialize and inject your controller as well. Something like this:

var $controller;
var $rootScope;

var scope;
var controller;

beforeEach(inject(function (_$controller_, _$rootScope_) {

    $controller = _$controller_;
    $rootScope = _$rootScope_;

    scope = $rootScope.$new();
    controller = $controller('ScopeController', { '$scope': scope });
}));

Upvotes: 1

Related Questions