角度单位测试

时间:2015-10-29 23:17:30

标签: javascript angularjs twitter-bootstrap jasmine karma-jasmine

我是这样的扩展bootstrap模式:

.directive("modal", [function(){
    var controller = function($scope, $attrs, $element, $uibModal){
        var defaultOptions = {
            title: "Modal title",
            content: "Modal body",
            controller: "DefaultModalController",
            templateUrl: "js/dev/shared/directives/templates/default-modal-template.html"
        };

        $element.on($scope.event, function(){
            var userOptions = {
                title: $attrs.title,
                content: $attrs.content,
                templateUrl: $attrs.templateUrl,
                controller: $attrs.controller
            };
            options = angular.extend({},defaultOptions, userOptions || {});

            $uibModal.open({
                templateUrl: options.templateUrl,
                controller: options.controller,
                resolve: {
                    options: function () {
                        return options
                    }
                }
            });
        });
    };

    return {
        restrict: "A",
        scope: {
            event: "@"
        },
        controller: ["$scope", "$attrs", "$element", "$uibModal", controller]
    }
}])
.controller("DefaultModalController", ["$scope", "$modalInstance", "options",
        function($scope, $modalInstance, options){
    $scope.modalOptions = options;

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

我的测试看起来像这样:

DESCR

ibe("ModalDirective", ()=>{
    var element,
        compile,
        scope,
        controller;
    beforeEach(module("app.directive"));
    beforeEach(inject((_$compile_, _$rootScope_, _$controller_)=>{
        compile = _$compile_;
        controller = _$controller_;
        scope = _$rootScope_.$new();
        element = angular.element("<button modal>test</button>")
    }));

    it("should create default modal window", ()=>{

        element = compile(element)(scope);
        console.error(element.html());

        expect(true).toBeTruthy();
    })
});

但是当compile(element)(scope)正在执行时,我遇到了这个错误:

TypeError:'undefined'不是对象(评估'd.indexOf')         在(https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js:179

我该怎么办才能修复它?

[编辑]

我解决了这个问题,问题在于创建指令。 在指令定义中我有:

scope: {
    event: "@"
}

,当我将其更改为<button modal>test</button>时,我的模板为<button modal event='click'>test</button>问题已解决。

0 个答案:

没有答案