2016-10-06 4 views
4

나는 최종 2 각도 (2.0.1)를 사용하고 있습니다. 서비스를 제공하는 구성 요소가 있습니다. 그것은 그것을 사용하는 유일한 것이고, 이것이 포함 된 모듈이 아니라 그것을 제공하고 생성자에 주입되는 이유입니다.서비스를 제공하는 구성 요소에 대한 각도 2 테스트 사양

@Component({ 
    selector: 'my-comp', 
    templateUrl: 'my-comp.component.html', 
    styleUrls: ['my-comp.component.scss'], 
    providers: [MyService], 
}) 
export class MyComponent { 

    constructor(private myService: MyService) { 
    } 
} 

사양을 구현하려고하면 오류가 발생합니다.

describe("My Component",() => { 

beforeEach(() => { 
    TestBed.configureTestingModule({ 
     declarations: [MyComponent], 
     providers: [ 
      { 
       provide: MyService, 
       useClass: MockMyService 
      }, 
     ] 
    }); 

    this.fixture = TestBed.createComponent(MyComponent); 
    this.myService = this.fixture.debugElement.injector.get(MyService); 

}); 

describe("this should pass",() => { 

    beforeEach(() => { 
     this.myService.data = []; 
     this.fixture.detectChanges(); 
    }); 

    it("should display",() => { 
     expect(this.fixture.nativeElement.innerText).toContain("Health"); 
    }); 

}); 

그러나 서비스 제공 선언을 구성 요소에서 포함 모듈로 이동하면 테스트가 통과됩니다.

나는 테스트 베드 테스트 모듈은 모의 서비스를 정의하고 있기 때문에 가정하지만, 구성 요소가 생성 될 때 - 그것은 실제 구현과 함께 모의를 ... 우선

사람이 어떻게 구성 요소를 테스트하는 어떤 생각을 가지고 있습니까 서비스를 제공하고 모의 서비스를 사용합니까?

답변

13

@Component.providers은 테스트 베드 구성을 통해 제공하는 모의보다 우선하므로 무시해야합니다.

beforeEach(() => { 
    TestBed.configureTestingModule({ 
    declarations: [MyComponent] 
    }); 

    TestBed.overrideComponent(MyComponent, { 
    set: { 
     providers: [ 
     { provide: MyService, useClass: MockMyService } 
     ] 
    } 
    }); 
}); 

항목 :

+0

완벽! 어떻게 내가 문서에서 그것을 놓친 지 모르겠 :) –

관련 문제