AngularJS: контроллер не определен при тестировании директивы с контроллерами, использующими Jasmine

0

Мне нужно проверить контроллер, который использует моя директива. но не может ссылаться на контроллер.

directive.js

(function () {
    'use strict';

    angular
        .module('myModule')
        .directive('cabinet', function () {
            return {
                restrict: 'E',
                replace: true,
                controller: CabinetThumbnails,
                controllerAs: 'ctrl',
                bindToController: true,
                templateUrl: 'app/components/capture/cabinet.directive.html',
                scope: {
                    thumbnail: '='
                }
            };
        });    

    function CabinetThumbnails($uibModal, cabinetService, SweetAlert,
                               spinner, $state, $window) {
        var vm = this;

        vm.showImage = showImage;
        vm.deleteThumbnail = deleteThumbnail;

        function showImage() {
            if (vm.thumbnail.FileCategoryName === 'OpenDocument') {
                $window.open(vm.thumbnail.FileUrl);
            }
            else {
                $uibModal.open({
                    animation: true,
                    templateUrl: 'app/components/capture/cabinet.pop-up.html',
                    controller: ModalCtrl,
                    controllerAs: 'ctrl',
                    size: 'lg',
                    resolve: {
                        thumbnailData: function () {
                            return vm.thumbnail;
                        }
                    }
                });
            }
        }

        function deleteThumbnail() {
            //show the popup confirmation
            SweetAlert.swal({
                    title: 'Are you sure to delete ?',
                    text: 'You will not be able to recover the file once deleted !',
                    type: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#DD6B55',
                    confirmButtonText: 'Delete',
                    closeOnConfirm: true
                },
                function (isConfirm) {
                    if (isConfirm) {
                        spinner.show();
                        //call the service to delete here
                        cabinetService.deleteCabinetFile(vm.thumbnail.CabinetFileID)
                            .then(function (data) {
                                //validate the response
                                if (data != null && data.returnVal === -1) {
                                    SweetAlert.swal('You do not have access to delete ' +
                                        'the screen shot',
                                        'Please contact the owner of the screen shot!',
                                        'error');
                                } else {
                                    //load all the Thumbnails by reloading the page
                                    $state.reload();
                                }
                            })
                            .catch(function (err) {
                                SweetAlert.swal('Something went wrong !',
                                    'Please try again later !', 'error');
                            })
                            .finally(spinner.hide);
                    }
                });
        }

    }    

    function ModalCtrl($scope, $uibModalInstance, thumbnailData,
                       logger, cabinetService) {
        var ctrl = this;

        ctrl.thumbnailData = thumbnailData;
        ctrl.save = save;
        ctrl.cancel = cancel;

        //call this method to get executed while the directive loads to open the pop-up
        getComments();

        function getComments() {
            cabinetService
                .getComments(thumbnailData)
                .then(function (data) {
                    ctrl.comments = data;
                })
                .catch(function (err) {
                    logger.error('Unable to get comments, Please try later !',
                        {ttl: 20000});
                });
        }
    }
}());

MytestSpec.js:

'use strict';

describe('cabinet', function () {
    var el,
        CabinetThumbnailsController,
        scope;

    beforeEach(bard.appModule('myModule', bard.fakeLogger));

    // Initialize the controller and a mock scope
    beforeEach(function () {
        bard.inject('$controller', '$compile', '$rootScope', '$q', '$uibModal',
            'cabinetService', 'SweetAlert', 'spinner', '$state',
            '$window');

        scope = $rootScope.$new();

        el = angular.element('<div cabinet></div>', {$scope: scope});
        $compile(el)(scope);
        //CabinetThumbnailsController = el.controller('cabinet');
        CabinetThumbnailsController = $controller('CabinetThumbnails', {$scope: scope});
        $rootScope.$apply();
    });

    it('should be initialized', function () {
        expect(el).toBeDefined();
    });

    //controller testing
    it('CabinetThumbNails controller to be initialized', function () {
        expect(CabinetThumbnailsController).toBeDefined();            
    });

    it('CabinetThumbNails controller showImage method to be called', function () {
        expect(CabinetThumbnailsController.showImage).toHaveBeenCalled();
    });

});

оба следующих утверждения не работают

        CabinetThumbnailsController = el.controller('cabinet');
        CabinetThumbnailsController = $controller('CabinetThumbnails', {$scope: scope});

и, следовательно, вызов методов контроллера, как указано ниже, тоже не выполняется:

expect(CabinetThumbnailsController.showImage).toHaveBeenCalled();
Теги:
karma-jasmine
jasmine
angularjs-directive

1 ответ

1
Лучший ответ

Разделил мой контроллер на другой файл и самостоятельно проверил контроллер. Не удалось получить подход к тестированию контроллера вместе с директивой.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню