2013-09-10 11 views
10

私は、サービス 'Inputs'をモジュール 'Puts'に定義しています。これは第2サービス 'InputCreator'に依存します。私はInputsサービスをテストするためにInputCreatorサービスをスタブする必要があります。モック角度サービスの依存関係を挿入する

私はanswer hereを理解しているので、自分のスタブサービスを含むモジュールを作成し、新しい 'Test'モジュールを作成し、テスト対象モジュールとスタブモジュールを依存関係として指定する必要があります。その後、インジェクタからサービスを引き出します。これと同じように: ' - インプット不明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.mock.moduleではなくangular.moduleを使用していたことです。これは、便宜上、angular-mockによってモジュールとして参照されています。彼らはまったく同じものではありません!

さらに、テスト中のモジュールを初期化する前に、モックサービスをangular.mock.moduleで初期化するだけで十分です。上にリンクされた質問に示唆されているように、このモジュールを第3のモジュールビジネスにラップする必要はありません。依存モジュールがすでに存在する場合、あなたはまだ上記のすべてを行うことができますか、あなたは$インジェクタからサービスを取得でき

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 –

関連する問題