0

我開始學習如何用茉莉花做單元測試。我在互聯網上閱讀了很多,但我無法解決我的問題。uibModal provider unknown unitTest

我有一個指令,它有一個控制器。當我點擊一個元素時,該控制器正在使用服務$ 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。

我可以用另一種方式注入這項服務嗎?我做錯了什麼?

P.S:我已閱讀本Testing AngularUI Bootstrap modal instance controller

Angular ui bootstrap $uibModalInstance breaks down unit tests

Mocking $modal in AngularJS unit tests

回答

0

最後我解決它。這是一個愚蠢的錯誤。我導入了一個我在測試中缺少的模塊。之後,我可以嘲笑我的服務,並使用它,沒有像這樣的問題。

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

試試這個:

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