Skip to content

[NEW TEST] Testing for interceptor failureΒ #1503

@joebowbeer

Description

@joebowbeer

Is there an existing issue for this?

  • I have searched the existing issues

Feature Test To Be Requested

I was using your CatInterceptor test as a template for a request interceptor test.

It was not clear how to test for an expected failure. Below is sketch of the test I created:

class FailingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    throw new Error();
  }
}

const interceptor = new FailingInterceptor();

// create the mock CallHandler for the interceptor
const next = {
  handle: () => EMPTY,
};

it('should fail', () => {
  const ctxMock = createMock<ExecutionContext>({
    switchToHttp: () => ({
      getRequest: () => ({
        headers: {},
      }),
    }),
  });
  expect(() =>
    interceptor
      .intercept(ctxMock, next)
      .subscribe({ complete: () => fail() }),
  ).toThrowError(Error);
  expect(fnAfterFailure).not.toHaveBeenCalled();
});

I also discovered that failures in the Observable subscriber would result in test timeouts. That is, the test would fail but it would also timeout because done was never called.

To be resilient in the event of unexpected failure, I think the cat interceptor test should be modified:

    it('should successfully return', (done) => {
      interceptor.intercept({} as any, next).subscribe({
        next: (value) => {
          try {
            expect(value).toEqual({ data: returnCat });
          } catch(error) {
            fail(error);
          }
        },
        error: (error) => {
          fail(error);
        },
        complete: () => {
          done();
        },
      });
    });

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions