我们如何在angularJS控制器中进行单元测试功能

时间:2015-09-15 23:02:40

标签: javascript angularjs unit-testing modal-dialog jasmine

这是代码:

(function(){

"use strict";

angular.module("dataModule")
       .controller("panelController", ["$scope", "$state", "$timeout", "$modal", panelController]);

function panelController($scope, $state, $timeout, $modal){

    $scope.property = "panelController";
    //how do we do unit test on openCancelWarning.
    //i did not find a way to get openCancelWarning function in Jasmine.
    function openCancelWarning () {
        var cancelModal = $modal.open({
            animation: true,
            backdrop: "static",
            templateUrl: "pages/data/cancel-warning.html",
            controller: "cancelWarningController",
            size: "sm",
            resolve: {
                items : function() {
                    return {
                        warningTitle : "Are you Sure?",
                        warningMessage: "There are unsaved changes on this page. are you sure you want to navigate away from this page?Click OK to continue or Cancel to stay on this page"
                    };
                }
            }
        });
        return cancelModal;
    }

    var resultPromise = openCancelWarning();
    var result;
    resultPromise.result.then(function(response){
            result = response;
    }); 
}

angular.module("dataModule")
       .controller("cancelWarningController", ["$scope", "$modalInstance", "items", cancelWarningController]);

function cancelWarningController($scope, $modalInstance, items){
    $scope.warningTitle = items.warningTitle;
    $scope.warningMessage = items.warningMessage;

    $scope.cancel = function() {
        $modalInstance.close(false);
    };

    $scope.ok = function() {
        $modalInstance.close(true);
    };
}
}());

这是我的茉莉花单元测试代码。

describe("Controller: panelController", function () {

beforeEach(module("dataModule"));

var panelController, scope;

var fakeModal = {
    result : {
        then: function(confirmCallback) {
            this.confirmCallback = confirmCallback;
        }
    },
    close: function(confirmResult) {
        this.result.confirmCallback(confirmResult);
    }
};

beforeEach(inject(function($modal) {
    spyOn($modal, "open").andReturn(fakeModal);
}));

beforeEach(inject(function ($controller, $rootScope, _$modal_) {
    scope = $rootScope.$new();
    panelController = $controller("panelController", {
        $scope: scope,
        $modal: _$modal_
    });
}));

it('test should be true', function () {        
    var test;

    var testResult = panelController.openCancelWarning();
    testResult.close(true);
    testResult.then(function(response){
        test=response;
    });
    expect(test).toBe(true);      

});
});

我在Mocking $modal in AngularJS unit tests的帮助下写了上面的单元测试代码 我总是低于错误。

  

TypeError:'undefined'不是函数(评估'panelController.openCancelWarning()')

任何人都可以帮忙吗?

0 个答案:

没有答案