I am completely new to unit testing and I am implementing unit testing using jasmine/karma for the first time. I am facing few issues in understanding how I should implement testing by mocking for Http Post. I have gone through few solutions such as : solution1 and solution2
But still I have faced few issues in understanding them and have also faced few errors.
By following solution2 I have tried to implement as follows:
http.service.ts
update(id,password,url){
let content = {
"username": id,
"password":password,
}
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
return this.http.post(url,content,httpOptions).subscribe((data:any) => {
if(data.length){
return true;
}
else{
return false;
}
})
http.service.spec.ts
import { TestBed, inject } from '@angular/core/testing';
import { HttpClientModule } from '@angular/common/http';
import { HttpService } from './http.service';
import {HttpModule, XHRBackend,Response,ResponseOptions, Connection} from
'@angular/http';
import { of } from 'rxjs';
import { MockBackend } from '@angular/http/testing';
describe('HttpService', () => {
let mockbackend, service;
beforeEach(() => {TestBed.configureTestingModule({
imports:[HttpClientModule, HttpModule],
providers:[{
provide: XHRBackend, useclass: MockBackend
}]
})
});
beforeEach(inject([ XHRBackend], (_service,
_mockbackend) => {
service = _service;
mockbackend = _mockbackend;
}));
it('post method is successfull',() =>{
const status = 'success';
const username = '5555555';
const password = 'test';
const currentUserExpected = JSON.stringify({status:status});
const response = { status : status};
const responseOptions = new ResponseOptions();
responseOptions.body = JSON.stringify(response);
mockbackend.connections.subscribe(connection =>{
connection.mockRespond(new Response(responseOptions));
});
service.update(username,password).subscribe(respond =>{
expect(respond).toEqual(true)
})
})
The error I am receiving is this:
Error
Cannot read property 'connections' of undefined
Can someone please help me out in understanding where I am going wrong.
Also I would like to receive reference to any documentation which can help me better understand this.