angularunit-testingjestjsjasmine-marbles

How to trigger error and test the method?


I am doing angular service test. it works fine. But I unable to achieve the 100% of testing, since the error function not tested. I tried my best. but not able to come up with 100%. any one help me?

here is my service:

export class CandidateRegistrationManagementService {

    constructor(private http: HttpClient) { }

    getAvailabilityType(): Observable<ModelAvailabilityType> {
        return this.http.get<ModelAvailabilityType>(environment.setUpAndConfigUrl + `LookupTypeValue/LookupValueTypeDetails?LookupTypeName=AvailabilityType`)
            .pipe(
                map(events => {
                    return events;
                }),
                catchError(this.handleError)
            );
    }
    
    handleError(error: Response) {
        return throwError(error);
    }
}

my test case at present 75% i have covered. problem to with error testing. here is my try:

it('should throw error', () => {

        const httpError = {
            get: jest.fn(() => of(hot('#', {}, new Error('server error'))))
        };

        function handleError(error:any) {
            return throwError(error);
        }

        CRMService = new CandidateRegistrationManagementService(httpError as any);
        CRMService.getAvailabilityType().subscribe(data =>data, (error:any) => {
            catchError(handleError(error))
        })

    })

But my try not works. I am not get 100% of coverage. please looking for an help here.


Solution

  • Try using -- throwError rxjs operator, throwError will execute error block of your code.

       const httpError = {
                get: jest.fn(() => throwError(new Error('server error'))
            };