Reputation: 503
I am new in Karma and not getting how to write test case for POST method.
This is my service.ts file:-
constructor(private httpclient: HttpClient) { }
url = 'http://localhost:8047/some_url';
check: Check[];
public newBehaviour = new BehaviorSubject<Check[]>([]);
postRents(hire, bookingId, trackingId): Observable<Check> {
hire.bookingId = bookingId;
hire.trackingId = trackingId;
return this.httpclient.post<Check>(this.url, hire, {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
})
}).pipe(
tap(data => {
this.check.push(hire);
this.newBehaviour.next(this.check);
console.log(data);
})
);
How can I test POST for this code ?
EDIT:- not able to test POST for this
postRents(hire, bookingId, trackingId): Observable<Check> {
hire.bookingId = bookingId;
hire.trackingId = trackingId;
return this.httpclient.post<Check>(this.url, hire, {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
})
}).pipe(
tap(data => {
this.check.push(hire);
this.newBehaviour.next(this.check);
console.log(data);
})
);
getting error in method implementing
it('Check Serivice', () => {
const mockData: RentBook[] = [{
rentingId: 343,
userName: 'dwew',
phone: 242324,
bookId: '3442',
startDate: new Date(),
endDate: new Date('Wed November 20 2019 00:00:00 GMT+0530 (India Standard Time)'),
}];
service.postRents(mockData, bookId: '34', rentId:34).subscribe(
res => expect(res).toEqual(mockData)
);
httpTestingController.expectOne(req => req.url.includes('http://localhost:8047/renting-app/api/v1/rentings') && req.method === 'POST')
.flush(mockData);
httpTestingController.verify();
});
Any solution for passing argument data. not getting how to pass in test case.
Upvotes: 0
Views: 336
Reputation: 36
Use HttpTestingController
to write the test for service
HttpClientTestingModule
in your TestBed & use TestBed to
inject HttpTestingController
as a variable let mockHttp: HttpTestingController
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
...
})
mockHttp = TestBed.get(HttpTestingController);
describe('...', () => {
it('...', () => {
yourService.funcWhatToTest().subscribe(
res => expect(res).toEqual(yourMockData);
)
mockHttp.expectOne(req => req.url.includes('yourUrl') && req.method == 'POST' && ...)
.flush(yourMockData);
mockHttp.verify();
}
})
HttpTestingController
Upvotes: 1