数组不是JavaScript单元测试angular

时间:2018-11-13 10:07:33

标签: javascript angularjs

我有一个用于创建对话框的工厂:

module myModule {
    export class myDialog {
        constructor(private $uibModal: ng.ui.bootstrap.IModalService) {}
        showDialog() {
            var options: ng.ui.bootstrap.IModalSettings = {
                templateUrl: '/dialog.html',
                size: "lg",
                controller: ['$scope', '$uibModalInstance', function($scope: any, $uibModalInstance: ng.ui.bootstrap.IModalServiceInstance) {
                    $scope.cancel = () => {
                        $uibModalInstance.close({
                            doAction: 'close'
                        });
                    }
                }],
                controllerAs: '$ctrl'
            };
            return this.$uibModal.open(options).result;
        }

        static factory(): any {
            const dialog = ($uibModal: ng.ui.bootstrap.IModalService) => new myDialog($uibModal);
            dialog.$inject = ['$uibModal'];
            return dialog;
        }
    };
    angular.module('myModule').factory('myDialog', myDialog.factory());
}

如您所见,对于controller注入,我使用了数组(内联数组注释)以便在最小化javascript文件时起作用。

我使用bardjs创建了一个测试:

describe('My dialog service', function() {
    beforeEach(function() {
        module('myModule', function($provide) {
            $provide.factory('$uibModalInstance', function() {
                return {
                    close: function(result) {
                        return result;
                    }
                };
            });
        });
        module('myModule');
        bard.inject('$uibModal', '$uibModalInstance', '$http', '$httpBackend', '$q', '$rootScope', 'myDialog');
        bard.mockService($uibModal, {
            open: function(options) {
                return {
                    result: options
                };
            }
        });
        spyOn($uibModal, 'open').and.callThrough();
        spyOn($uibModalInstance, 'close').and.callThrough();
    });

    it('expect it to be defined', function() {
        expect(myDialog).toBeDefined();
    });
});

但是我得到了错误:

  

TypeError:数组不是构造函数(正在评估   'options.controller(scope,$ uibModalInstance)')

为什么?如何解决?

1 个答案:

答案 0 :(得分:0)

options对象外部声明控制器,并使用$inject注入依赖项。

showDialog() {
    const ctrl = function($scope: any, $uibModalInstance: ng.ui.bootstrap.IModalServiceInstance) {
                $scope.cancel = () => {
                    $uibModalInstance.close({
                        doAction: 'close'
                    });
                }
            };
    ctrl.$inject = ['$scope', '$uibModalInstance'];

    var options: ng.ui.bootstrap.IModalSettings = {
            templateUrl: '/dialog.html',
            size: "lg",
            controller: ctrl,
            controllerAs: '$ctrl'
    };
    return this.$uibModal.open(options).result;
}
相关问题