shadowFax
shadowFax

Reputation: 11

How to unit test Nest Interceptor

I'm looking for some insight on unit testing an interceptor in Nestjs, please bare with my limited understanding of unit tests as I'm still fairly new to them, so feel free to explain concepts that seem rather trivial, as I would appreciate it nonetheless!

Just for the sake of this question, I'll borrow the code from the Nestjs documentation, specifically, the LoggingInterceptor, since that's the one I implemented in my project.

Here is the logging interceptor from the official docs.

import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    console.log('Before...');

    const now = Date.now();
    return next
      .handle()
      .pipe(
        tap(() => console.log(`After... ${Date.now() - now}ms`)),
      );
  }
}

I've tried and failed a few times at setting up a simple unit test that just shows the console.log was called twice, once before the next call is made, and once after.

Upvotes: 1

Views: 1764

Answers (1)

alessia pileri
alessia pileri

Reputation: 152

You can easily create a Unit Test for the logger interceptor in this way:

  it('should log to console', async done => {
    const mockHandler: CallHandler = {
      handle: () => throwError(new Error('try and retry')),
    };
    const mockExecutionContext = ({} as unknown) as ExecutionContext;
    const spy = jest.spyOn(console, 'log');

    loggerInterceptor
      .intercept(mockExecutionContext, mockHandler)
      .subscribe(
        _ => _,
        () => {
          expect(spy).toBeCalled();
          done();
        },
      )
      .unsubscribe();
  });

Upvotes: 2

Related Questions