0

我正在努力了解如何使用 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 答案,但看不到我哪里出错了。

4

1 回答 1

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);

    });

});
于 2013-08-15T15:42:13.280 回答