2017-10-16 5 views
0

각도 4로 앱을 작성하고 http 요청과 함께 ngOnInit 기능이 있습니다. 단위 테스트를 작성하고 싶지만 요청을 조롱하는 방법을 모릅니다.각도 4의 모의 HTTP 요청

beforeEach(async(() => { 
TestBed.configureTestingModule({ 
    imports: [ HttpClientModule, HttpModule ], 
    declarations: [ ServBComponent ], 
    providers : [ 
    { provide: 'someurl', useValue: '/' }, 
    { provide: XHRBackend, useClass: MockBackend } 
    ] 
}) 
.compileComponents().then(() => { 
    fixture = TestBed.createComponent(ServiceBrokersComponent); 
    component = fixture.componentInstance; 
}); 
it('should get the servb list', async(inject([XHRBackend], (mockBackend) => { 
    mockBackend.connections.subscribe((connection) => { 
    connection.mockRespond(new Response(new ResponseOptions({ 
     body: data 
    }))); 
    }); 
    fixture.detectChanges(); 
    fixture.whenStable().then(()=> { 
    console.log('anything'); 
    }); 
}))); 

을했지만 작동하지 않습니다

ngOnInit() { 
this.http.get<any>('someurl', { 
    headers: new HttpHeaders().set('Authorization', 'authorization'`) 
}) 
.subscribe(
    (res) => { 
    this.servB = res.items 
    .map((item) => { 
     return new ServB(item) 
    }); 
    } 
); 
} 

는 내 단위 테스트는 지금까지 다음과 같습니다. 여전히 서버에서 데이터를 요청하고 조롱 된 값을 반환하지 않습니다. 게다가 'whenStable()'이 전에 실행되는 모든 것 ... 내가 뭘 잘못하고 있니?

답변

0

는이 같은 HttpClientModule 대신 HttpClientTestingModule를 가져와야 :

beforeEach(() => { 
    TestBed.configureTestingModule({ 
    imports: [HttpClientTestingModule], 
    providers: [ 
     HttpService 
    ] 
    }); 
}); 
+0

그것이 불행하게도 –

+0

도움이 도움이됩니까하지 않습니다 http://www.syntaxsuccess.com/viewarticle/mocking-http-request - with-httpclient-in-angular – DeborahK