2016-07-06 34 views
2

我目前正在研究一個大的AngularJS應用程序,非常基於優秀的AngularJS Styleguide by John Papa如何在AngularJS應用程序中模擬/存根激活()方法

他的一個建議是使用activate()方法作爲每個控制器的一種引導程序。這使您的代碼結構清晰,並且您立即知道引導啓動的位置。很多時候,我用它來加載數據(我更喜歡通過路由解析)。

我面臨的問題是如何在不運行activate()-方法的情況下在下面的代碼示例中單元測試methodUnderTest()-方法。

(function() { 
    'use strict'; 

    angular 
     .module('myApp', []) 
     .controller('ControllerUnderTest', ControllerUnderTest); 

    ControllerUnderTest.$inject = []; 

    /* @ngInject */ 
    function ControllerUnderTest() { 
     var vm = this; 

     // attach functions to vm 
     vm.activate = activate; 
     vm.methodUnderTest = methodUnderTest; 

     // activate 
     activate(); 

     function activate() { 
      // controller start-up logic 
     } 

     function methodUnderTest() { 
      // how to test this method, without running the activate() method 
     } 
})(); 

下面是測試代碼,我現在有,但你希望它會永遠運行activate()方法(這是不是我想要的)。

(function() { 

    var scope, createController; 

    beforeEach(module('myApp')); 

    describe('ControllerUnderTest', function(){ 
     beforeEach(inject(function($rootScope, $controller) { 
      scope = $rootScope.$new(); 

      createController = function() { 
       return $controller('ControllerUnderTest', { 'scope': scope }); 
      }; 
     })); 

     it('should be defined', function() { 
      var controller = createController(); 
      expect(controller).toBeDefined(); 
     }); 

     it('should have a methodUnderTest', function() { 
      var controller = createController(); 
      expect(controller.methodUnderTest).toBeDefined(); 
     }); 

    }); 
})(); 

如何測試ControllerUnderTest.methodUnderTest()而不運行activate()方法?

+0

你不得不嘲笑激活方法內的所有來電,不執行初始化方法不是一個很好的測試 – fantarama

+0

感謝fantarama,但如果有發生了很多的東西'activate()'方法有很多不同的依賴關係(服務),這對於methodUnderTest來說沒有用? –

+1

無用的測試服務必須用無效實現或固定返回值嘲笑 – fantarama

回答

1

在模塊單元測試中,您必須模擬超出測試範圍的所有依賴關係。

成才,如:

beforeEach(module(function ($provide) { 
    $provide.service("myService", function() { 
     this.myMethod = function() { 
      return "myValue"; 
     }; 
    }); 
})); 
相關問題