2013-09-10 4 views
10

두 번째 서비스 인 'InputCreator'에 의존하는 모듈 'Puts'에 정의 된 'Inputs'서비스가 있습니다. 입력 서비스를 테스트하기 위해 InputCreator 서비스를 스텁 (stub)해야합니다.모의 각도 서비스 의존성 주입하기

나는 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.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 –

관련 문제