如何在指令中使用Jasmine控制器对角度进行单元测试

时间:2015-08-05 19:05:13

标签: angularjs jasmine

所以我正在尝试学习如何使用Angular对Jasmine进行单元测试。我有一些单元测试工作,但这一次让我很难过。我在我的测试中取出了警报数组,你可以把它变成任何阵列..但是如何模仿这个并让它工作真的让我很难过。我认为这个对象会存在。

(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;
}]);
})()

我有一个看起来像

的测试
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);
    });

});

});

错误我看起来像

TypeError:无法读取属性&#39; AlertList&#39;未定义的

1 个答案:

答案 0 :(得分:1)

您还必须初始化并注入控制器。像这样:

// Assigns a value to it
model.assign($scope, 42);