uib模态提供程序未知单元测试

uibModal provider unknown unitTest

本文关键字:未知 单元测试 程序 模态 uib      更新时间:2023-09-26

我开始学习如何用茉莉花进行单元测试。我在互联网和SO上阅读了很多,但我无法解决我的问题。

我有一个指令,它有一个控制器。当我单击元素时,该控制器正在使用服务$uibModal打开模式。我正在尝试从测试中注入该服务,但我不能。我读了很多帖子,说我必须通过一个实例。我正在尝试这样做,但我不能。请任何帮助将不胜感激。

.controller('myController', ['$scope', '$uibModal', function($scope, $uibModal){
    var self = this;
    //OTHER CODE
    self.openMyModal = function(dataInput) {
        var modalInstance = $uibModal.open({
            animation: true,
            bindToController: true,
            templateUrl: 'app/myComponent/modals/component-modal.html',
            controllerAs: 'componentModalCtrl',
            controller: 'componentModalController',
            windowClass: 'semi-modal semi-modal--large',
            scope: $scope
        })
    }
    //OTHER CODE
}

这是我试图模拟这种模态的测试。

beforeEach(function(){
    angular.mock.module('templates');
    angular.mock.module('app.components.myComponent');
    angular.mock.inject(function($compile, $rootScope, $templateCache, $controller){
        scope = $rootScope;
        modalInstance = { close: function(){}, dismiss: function(){}, open: function(){}
    };
    //Initializing element and doing compile and digest
    controller = $controller('myController', {$scope: scope, $uibModal: modalInstance});
})

我收到错误

未知提供商:$uibModalProvider <- $uibModal。

我可以通过其他方式注入此服务吗?我做错了什么?

PS:我已经阅读了这个测试角度UI引导模态实例控制器

Angular UI 引导程序$uibModalInstance分解单元测试

AngularJS单元测试中的模拟$modal

试试这个:

beforeEach(module(function ($provide) {
    $provide.service("$uibModal", function () {
        // mock methods here
    });
}));

最后我解决了。这是一个愚蠢的错误。我导入了一个在测试中缺少的附加模块。之后,我可以模拟我的服务并使用它,没有任何问题。

angular.mock.inject(function($compile, $rootScope, $templateCache, $controller, $uibModal){
    scope = $rootScope;
    uibModal = $uibModal;
    element = angular.element('<directive-tree input-tree=inputTree subsystem=subsystem></directive-tree>');
    $compile(element)(scope);
    scope.$digest();
    controller = $controller('directiveTreeController', {$scope: scope, $uibModal: uibModal});
  });