Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing of catcherror pipe function in angular service

I try to understand how to test this function. From (err)=>{ line, it's showing as an uncovered statement. service.ts

Deletevote(inp) {
   console.log(inp);
     
   return this.http.post(environment.apiUrl + '/api/reset/abc', inp).pipe(
      catchError((err) => {
         console.log('error caught in service');
         console.error(err);
         return throwError(err);
      })
   );
}

I have created this test case for positive flow, but err part is still not covered. Please guide me about how to create the error.

service.spec.ts

const Mockcolor = 'green';
const MockGen = 'male';

it('submitnominGreen', () => {
    service.Deletevote(DeleteObj).subscribe((posts) =>{
      expect(posts).toEqual([Mockcolor,MockGen], 'should check mock data');
    });
    const req =  httpTestCtrl.expectOne(environment.apiUrl + '/api/reset/abc');
    expect(req.request.method).toBe('POST');
    expect(req.cancelled).toBeFalsy();
    req.flush([Mockcolor,MockGen])
});

1 Answers

First of all, the code inside the subscribe of the unit test would not be executed. Karma would wait for all the sync execution to be finished and would consider the test finished before the async callback would be executed. As a solution, you might use the done callback to indicate when is the test finished manually.

You did a great job leveraging the HttpTestingModule for testing. It allows you to test the errors easily as well. Instead of req.flush you might use the req.error method to simulate the HTTP error.

it('submitnominGreen', (done) => {
    const mockError = {error: 'someError'} as ErrorEvent;
    service.Deletevote(DeleteObj).subscribe(() => {}, (thrownError) =>{
      expect(thrownError.error).toEqual(mockError);
      done();
    });
    const req =  httpTestCtrl.expectOne(environment.apiUrl + '/api/reset/abc');
    req.error(mockError);
});

Take a look into the Error handling section of this nice article: Testing Angular HTTP Communication. It would be of help for some other scenarios as well.

like image 70
IAfanasov Avatar answered Jul 05 '26 08:07

IAfanasov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!