在AngularUI模态控制器单元测试

时间:2016-01-22 20:03:05

标签: angularjs unit-testing jasmine angular-bootstrap

我正在使用Angular-Bootstrap模态,并且有一个基本的控制器,如下所示:

.controller('DashboardHelpController', ['$scope', '$uibModal', function ($scope, $uibModal) {

    var dhc = this;

    dhc.open = function (size, resource) {
        var modalInstance = $uibModal.open({
            templateUrl: 'resourcePlayModal.html',
            controller: 'ModalInstanceCtrl as mic',
            size: size,
            resolve: {
                resource: function () {
                    return resource;
                }
            }
        });
    };
}])

它调用标准模态实例控制器:

.controller('ModalInstanceCtrl', ['$uibModalInstance', 'resource', function ($uibModalInstance, resource) {
    this.resource = resource;

    this.cancel = function () {
        $uibModalInstance.dismiss();
    };
}])

这是我的单元测试,模仿another SO post

describe('Modal controller', function () {
    var modalCtrl, scope, modalInstance;

    beforeEach(module('MyApp'));

    // initialize the controller and a mock scope
    beforeEach(inject(function ($controller, $rootScope) {
        scope = $rootScope.$new();

        modalInstance = {
            // create a mock object using spies
            close: jasmine.createSpy('modalInstance.close'),
            dismiss: jasmine.createSpy('modalInstance.dismiss'),
            result: {
                then: jasmine.createSpy('modalInstance.result.then')
            }
        };

        modalCtrl = $controller('DashboardHelpController', {
            $scope: scope,
            $uibModalInstance: modalInstance
        });
    }));

    it('should instantiate the mock controller', function () {
        expect(modalCtrl).not.toBeUndefined();
    });

    it('should have called the modal dismiss function', function () {
        scope.cancel;
        expect(modalInstance.dismiss).toHaveBeenCalled();
    });
});

问题是在范围内找不到取消功能:

  

使用['cancel'调用的预期间谍modalInstance.dismiss   ]但它从未被召唤过。

更新:我原本试图将cancel作为函数调用:

it('should have called the modal dismiss function', function () {
    scope.cancel();
    expect(modalInstance.dismiss).toHaveBeenCalled();
});

那不起作用。我上面的代码试图解决原始问题:

  

TypeError:scope.cancel不是函数

我对Controller as语法的使用有点复杂,但这应该有效。谢谢你的帮助。

1 个答案:

答案 0 :(得分:2)

scope.cancel是一个函数,但你不是这样调用的。

it('should have called the modal dismiss function', function () {
    scope.cancel();
    expect(modalInstance.dismiss).toHaveBeenCalledWith();
});

此外,永远不会在scope.cancel()上定义DashboardHelpController,即使这是您为测试创建的范围。您需要在仪表板控制器上创建一个方法,该方法在创建modalInstance之后调用模态实例close方法。

var modalInstance = $uibModal.open({
...
dhc.cancel = function ()  {
    modalInstance.dismiss();
}