Giter VIP home page Giter VIP logo

Comments (3)

micalevisk avatar micalevisk commented on July 22, 2024 3

@jmcdo29 I was thinking on adding a very basic sample that uses that TimeoutInterceptor just to demonstrate how we can write an unit test for the timeout operator of rxjs. But I don't think this will be that useful as it doesn't do anything fancy for the nestjs side, it just uses the API of rxjs-marbles lib to play with rxjs.

from testing-nestjs.

micalevisk avatar micalevisk commented on July 22, 2024

regarding testing interceptors, given a TimeoutInterceptor that looks like this:

import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
  RequestTimeoutException,
} from '@nestjs/common';
import ms from 'ms';
import { Observable, throwError, TimeoutError } from 'rxjs';
import { catchError, timeout } from 'rxjs/operators';

export class TimeoutInterceptor implements NestInterceptor {
  static TIMEOUT_RESPONSE_TIME_MS = ms('5s');

  intercept(_ctx: ExecutionContext, next: CallHandler): Observable<unknown> {
    return next.handle().pipe(
      timeout(TimeoutInterceptor.TIMEOUT_RESPONSE_TIME_MS),
      catchError((err) => {
        if (err instanceof TimeoutError) {
          return throwError(new RequestTimeoutException());
        }
        return throwError(err);
      }),
    );
  }
}

I've made an unit test for it, timeout.interceptor.spec.ts:

import { createMock } from '@golevelup/ts-jest';
import { CallHandler, ExecutionContext, RequestTimeoutException } from '@nestjs/common';
import { throwError } from 'rxjs';
import { marbles } from 'rxjs-marbles/jest';

import { TimeoutInterceptor } from '@/api/interceptors/timeout.interceptor';

describe('TimeoutInterceptor', () => {
  const TIMEOUT = TimeoutInterceptor.TIMEOUT_RESPONSE_TIME_MS;
  let timeoutInterceptor: TimeoutInterceptor;

  beforeEach(() => {
    timeoutInterceptor = new TimeoutInterceptor();
  });

  it(`should return the data, when the request handler take less than ${TIMEOUT}ms to execute`,
    marbles((m) => {
      const ctx = createMock<ExecutionContext>();
      const expectedData = {};
      const next: CallHandler = {
        handle: () => m.cold('(e|)', { e: expectedData }),
      };

      const handlerData$ = timeoutInterceptor.intercept(ctx, next);

      /** Marble emiting the value `expectedData` and complete. */
      const expected$ = m.cold('(e|)', { e: expectedData });
      m.expect(handlerData$).toBeObservable(expected$);
    }),
  );

  it(`should throw RequestTimeoutException (HTTP 408) error, when the request handler take ${TIMEOUT}ms to execute`,
    marbles((m) => {
      const ctx = createMock<ExecutionContext>();
      const next = {
        handle: () => m.cold(`${TIMEOUT}ms |`),
      };

      const handlerData$ = timeoutInterceptor.intercept(ctx, next);

      /** Marble emiting an error after `TIMEOUT` ms. */
      const expected$ = m.cold(`${TIMEOUT}ms #`, undefined, new RequestTimeoutException());
      m.expect(handlerData$).toBeObservable(expected$);
    }),
  );

  it(`should forward the error thrown`,
    marbles((m) => {
      const ctx = createMock<ExecutionContext>();
      const error = new Error('something');
      const next = {
        handle: () => throwError(error),
      };

      const handlerData$ = timeoutInterceptor.intercept(ctx, next);

      /** Marble emiting an error after `TIMEOUT`ms. */
      const expected$ = m.cold(`#`, undefined, error);
      m.expect(handlerData$).toBeObservable(expected$);
    }),
  );

  it(`should throw RequestTimeoutException (HTTP 408) error, when the request handler take ${2 * TIMEOUT}ms to run`,
    marbles((m) => {
      const ctx = createMock<ExecutionContext>();
      const next = {
        handle: () => m.cold(`${2 * TIMEOUT}ms |`),
      };

      const handlerData$ = timeoutInterceptor.intercept(ctx, next);

      /** Marble emiting the error after `TIMEOUT`ms. */
      const expected$ = m.cold(`${TIMEOUT}ms #`, undefined, new RequestTimeoutException());
      m.expect(handlerData$).toBeObservable(expected$);
    }),
  );
});

from testing-nestjs.

jmcdo29 avatar jmcdo29 commented on July 22, 2024

By the way @micalevisk if you want to put this into a sample app and add a PR that would be awesome! If not, I'm sure I'll get around to it eventually :)

from testing-nestjs.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.