2013-09-10 80 views
10

我有一個服務'Inputs',在模塊'Puts'中定義,依賴於第二個服務'InputCreator'。我需要存根InputCreator服務才能測試Inputs服務。注入模擬角度服務依賴關係

據我瞭解answer here,我應該創建一個包含我的存根服務的模塊,然後創建一個新的'測試'模塊,指定被測模塊,然後將存根模塊指定爲依賴關係。然後從注射器中提取服務。就像這樣: ' - 輸入未知InputsProvider <'

beforeEach(function() { 

    angular.module.('Puts'); // contains the service 'Inputs' 

    angular.module('Mocks',[]) 
    .service('InputCreator',function(){ 
     var mockInputs = { 
     //stubbed behaviour goes here 
     }; 
     return mockInputs; 
    }); 
    }); 

    angular.module('Test',['Puts', 'Mocks']; 

    inject(function($injector){ 
    Inputs = $injector.get('Inputs'); 
    }); 
}); 

然而,噴油器功能與響應。

我哪裏迷路了?

謝謝!

回答

21

想通了,我想我會回答我自己的問題。上面的大錯誤是使用angular.module而不是angular.mock.module,這是通過angular-mock作爲模塊引用的便利。他們根本不是一回事!

此外,只要在初始化待測模塊之前進行初始化,就可以使用angular.mock.module初始化模擬服務。沒有必要像上面鏈接的問題中所建議的那樣,將這些模塊封裝在第三個模塊中。即:

describe("Test Service", function() { 
    var TestService, getvaluestub; 

    beforeEach(function() { 

    // create mock service 
    var mock = {getvalue:function(){}} 

    angular.module('dependencymodule',[]) 
     .service('dependencyservice',function() { 
     return mock; 
     }); 

    //mock the function we are stubbing, (that, in this case, returns value 4) 
    getvaluestub = sinon.stub(mock,'getvalue')returns(4); 

    //instantiate your mock service 
    module('dependencymodule'); 

    //instantiate the module of the service under test, 
    //that depends on 'dependencyservice' mocked above 
    //(ie - testmodule includes the  service 'testservice') 
    module('testmodule'); 

    //inject your test service for testing 
    inject(function ($injector) { 
     TestService = $injector.get('testservice'); 
    }) 

    //tests go here..... 

如果相關模塊已經存在,你既可以依然做到以上的,或者你可以獲取從$噴油器的服務,將您的間諜和存根,以及>然後<實例化被測服務。間諜/存根的設置> <的依賴服務實例化之前很重要,否則它將在沒有它們的情況下被實例化。它看起來像這樣:

describe("Test Service", function() { 
    var TestService, DependencyService, getvaluestub; 

    beforeEach(function() { 

    // these modules are specified in the application 
    module('dependencymodule'); 
    module('testmodule'); 

    inject(function ($injector) { 
     DependencyService = $injector.get('testservice'); 

     getvaluestub = sinon.stub(DependencyService,'getvalue').returns(4); 

     OtherService = $injector.get('otherservice'); 
    }) 
    }); 

// test go here 

所以,你去了。希望這對搜索'將模擬注入角度服務'的人有用。

+0

非常感謝您的支持!以下是使用存根進行服務測試服務,控制器和過濾器的另一個示例。 https://gist.github.com/clouddueling/11188718 –