单元测试带有bootstrap-ui对话框的Angular js

时间:2013-08-15 09:33:37

标签: javascript angularjs jasmine angular-ui-bootstrap

我正在努力了解如何使用jasmine来单元测试在angularjs中创建bootstrap-ui对话框元素。 控制器:

MyModule.controller('BaseCtrl', ['$scope', '$routeParams', '$location', '$http', '$filter', '$data', '$locationParse', '$dialog', function ($scope, $routeParams, $location, $http, $filter, $data, $locationParse, $dialog) {

//[...Loads of other stuff...]

//method in question:

    $scope.delete = function() {

        var boxResult;

        if ($scope.record._id) {

            var msgBox = $dialog.messageBox('Delete Item', 'Are you sure you want to delete this record?', [{
            label: 'Yes',
            result: 'yes'
        }, {
            label: 'No',
            result: 'no'
        }]);

        msgBox.open()
        .then(function(result) {

            if (result === 'yes') {
                $http.delete('api/' + $scope.modelName + '/' + $scope.id).success(function() {
                        if (typeof $scope.dataEventFunctions.onAfterDelete === "function") {
                            $scope.dataEventFunctions.onAfterDelete(master);
                        }
                        $location.path('/' + $scope.modelName);
                    });
                }

                if (result === 'no') {
                    boxResult = result;
                };
        });
            //can't close the msxBox from within itself as it breaks it. OK for now. TODO Refactor.
            if (boxResult === 'no') {
                msgBox.close();
            }
        }
    }

}]);

经过测试:

describe('"BaseCtrl"', function(){

var $httpBackend;

beforeEach(function() {
    angular.mock.module('MyModule');
});

afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
});

describe('deletion confirmation modal', function() {

    var $scope, ctrl, $dialog, fakeDialog;


    beforeEach(function() {

        inject(function(_$httpBackend_, $rootScope, $routeParams, $controller, $location, _$dialog_){

             $dialog = _$dialog_;


            fakeDialog = function (title, msg, btns) {
                return {
                    open: function () {
                        return {
                             then: function (callback) {
                                  callback('ok'); // 'ok' will be set to param result
                             }
                         }
                    }
                }
             };




            $httpBackend = _$httpBackend_;
            $httpBackend.whenGET('api/schema/collection').respond({"email":{"enumValues":[],"regExp":null,"path":"email","instance":"String","validators":[],"setters":[],"getters":[],"options":{"form":{"directive":"email-field"}},"_index":null,"$conditionalHandlers":{}}});
            $location.$$path = '/collection/new';
            $scope = $rootScope.$new();
            ctrl = $controller("BaseCtrl", {$scope: $scope, $dialog: $dialog});
            $httpBackend.flush();

            spyOn($dialog, 'messageBox').andReturn(fakeDialog);


        });

    });

    it('should inject bootstrap-ui dialog controller', function() {

         expect($dialog).toBeDefined();



    });


    it('should be displayed when $scope.delete() is called', function() {

        $scope.record._id = 1;
         $scope.delete();

        // console.log(dialog.messageBox);

        // expect(dialog.open).toHaveBeenCalled();

    });

});

});

我收到错误:

PhantomJS 1.9 (Mac) "BaseCtrl" deletion confirmation modal should be displayed when $scope.delete() is called FAILED
TypeError: 'undefined' is not a function (evaluating 'msgBox.open()')
    at /Users/steveclements/work/live/forms-angular/app/js/controllers/base.js:632
    at /Users/steveclements/work/live/forms-angular/test/unit/baseControllerSpec.js:735

如果我删除了fakeDialog方法(以及其他相关的测试代码),我会收到错误:

PhantomJS 1.9 (Mac) "BaseCtrl" deletion confirmation modal should be displayed when $scope.delete() is called FAILED
TypeError: 'undefined' is not an object (evaluating 'msgBox.open')
    at /Users/steveclements/work/live/forms-angular/app/js/controllers/base.js:632
    at /Users/steveclements/work/live/forms-angular/test/unit/baseControllerSpec.js:735

区别是'msgBox.open'与'msgBox.open()'所以我不认为模拟是问题。我已经阅读了很多有关此问题的其他SO答案,但看不出我出错的地方。

1 个答案:

答案 0 :(得分:0)

我将测试代码更改为:

describe('deletion confirmation modal', function() {

    var $scope, ctrl, $dialog, fakeDialog, provider, resolveCallback;

    //this fake object replaces the actual dialog object, as the functions are not visible to the test runner.
    fakeDialog = {

        isOpen: false,

        open: function() {
            fakeDialog.isOpen = true;

            return {
                then: resolveCallback
            };
        },

        close: function() {
            return true;
        }

    };

    resolveCallback = function(callback) {

            }

    beforeEach(function() {

        module(function($dialogProvider) {
            provider = $dialogProvider;
        });

        inject(function(_$httpBackend_, $rootScope, $routeParams, $controller, $location, _$dialog_) {

            $dialog = _$dialog_;

            $httpBackend = _$httpBackend_;
            $httpBackend.whenGET('api/schema/collection').respond({
                "email": {
                    "enumValues": [],
                    "regExp": null,
                    "path": "email",
                    "instance": "String",
                    "validators": [],
                    "setters": [],
                    "getters": [],
                    "options": {
                        "form": {
                            "directive": "email-field"
                        }
                    },
                    "_index": null,
                    "$conditionalHandlers": {}
                }
            });
            $location.$$path = '/collection/new';
            $scope = $rootScope.$new();
            ctrl = $controller("BaseCtrl", {
                $scope: $scope,
                $dialog: $dialog
            });
            $httpBackend.flush();

            spyOn($dialog, 'messageBox').andReturn(fakeDialog);
            $scope.record._id = 1;


        });

    });

    it('provider service should be injected', function() {
        expect(provider).toBeDefined();
    });

    it('dialog service should be injected', function() {
        expect($dialog).toBeDefined();
    });

    it('dialog messageBox should be defined', function() {

        $scope.delete();

        expect($dialog.messageBox).toHaveBeenCalled();


    });


    it('should be displayed when $scope.delete() is called', function() {

        $scope.delete();

        expect(fakeDialog.isOpen).toEqual(true);

    });

});