NoobCoder
NoobCoder

Reputation: 503

writing karma test case for post and get service in angular 8

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

Answers (1)

Hai Vu
Hai Vu

Reputation: 36

Use HttpTestingController to write the test for service

  • Import HttpClientTestingModule in your TestBed & use TestBed to inject HttpTestingController as a variable
  • Here is a quick example:
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();
  }
})
  • There would be a lot of resources online for this test. Search with keyword HttpTestingController

Upvotes: 1

Related Questions