I write an app in Angular 4 and I've got ngOnInit function with http get request. I want to write unit test, but don't know how to mock the request.
ngOnInit() {
this.http.get<any>('someurl', {
headers: new HttpHeaders().set('Authorization', 'authorization'`)
})
.subscribe(
(res) => {
this.servB = res.items
.map((item) => {
return new ServB(item)
});
}
);
}
and my unit test so far looks like this:
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');
});
})));
but it doesn't work. It still requests data from the server, doesn't return the mocked value. Plus everything that is after 'whenStable()' is executed before... What am I doing wrong?