0

I know there are some similar questions but couldn't find one to solve my issue.

So I have the following test (with 6 expectations):

  it('should redirect to error page when there is a 403 error', fakeAsync(() => {
    const mockError403Response: HttpErrorResponse = new HttpErrorResponse({
      error: '403 error',
      status: 403,
      statusText: 'Forbidden'
    });

    httpClient.get("/v1/test").subscribe(_ => { },
      (error: HttpErrorResponse) => {
        expect(error).toBeTruthy();
        expect(routerSpy.navigate).toHaveBeenCalled();
        expect(routerSpy.navigate).toHaveBeenCalledWith(['/error', 403]);
        expect(error.status).toEqual(mockError403Response.status);
        expect(error.error).toContain(mockError403Response.error);
        expect(error.statusText).toContain(mockError403Response.statusText);
      });

    let request: TestRequest;
    request = httpTestingController.expectOne("/v1/test");
    request.flush(mockError403Response);
    tick(500);
  }));

And I get the warning:

Spec 'should redirect to error page when there is a 403 error' has no expectations.

Any suggestion on how to solve this?

FMR
  • 173
  • 7
  • 17

1 Answers1

1

I am thinking, it never goes inside of your error block in your subscribe.

You have to pass a 2nd object for an error response in the flush. Right now, your test will go into the _ => { } of the subscribe block.

Try this:

 it('should redirect to error page when there is a 403 error', fakeAsync(() => {
    const mockError403Response: HttpErrorResponse = new HttpErrorResponse({
      error: '403 error',
      status: 403,
      statusText: 'Forbidden'
    });

    httpClient.get("/v1/test").subscribe(_ => { 
       // Call Jasmine fail to ensure if it comes here, the test is a failure.
       // Before your test was traversing here.
       fail(); 
    },
      (error: HttpErrorResponse) => {
        // ensure you see this log.
        console.log('!! Making assertions !!');
        expect(error).toBeTruthy();
        expect(routerSpy.navigate).toHaveBeenCalled();
        expect(routerSpy.navigate).toHaveBeenCalledWith(['/error', 403]);
        expect(error.status).toEqual(mockError403Response.status);
        expect(error.error).toContain(mockError403Response.error);
        expect(error.statusText).toContain(mockError403Response.statusText);
      });

    let request: TestRequest;
    request = httpTestingController.expectOne("/v1/test");
    // modify this line
    request.flush(mockError403Response, { status: 403, statusText: 'Forbidden' });
    tick(500);
  }));

Check this out on how to mock an Http error.

AliF50
  • 16,947
  • 1
  • 21
  • 37