Comments (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.
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.
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)
- About import {DocumentQuery} from 'mongoose' at mongo-sample
- Suggestion: convert testing-nestjs into monorepo with Lerna HOT 3
- [Question] How I mock another service method? HOT 8
- Suggestion: create tests for Prisma (alternative to TypeORM) HOT 7
- [FAILING TEST] Unit testing a NestJS Service that consumes a TypeORM Repository HOT 6
- [NEW TEST] KnexJs Sample test HOT 1
- Multiple mocked dependencies with the same content HOT 5
- [NEW TEST] Bull HOT 4
- Prisma transactions and rollbacks now available HOT 2
- [NEW TEST] - (Contract Testing) - Incorporate NestJS Consumer Driven Contract testing with nestjs-pact HOT 6
- README refers to non-existing cat.integration.spec.ts HOT 3
- Test against Solidity smart contracts
- [NEW TEST] Tests for mikro-orm
- [NEW TEST] Sequelize transactions HOT 1
- Add code comment for documenting the tests. HOT 1
- Unable to commit the file in file-up-and-down-sample HOT 1
- Can't push to sidebranch for PR - getting permission denied HOT 1
- I can't seem to make the tests fails anywhere so far HOT 3
- npm install doesn't work
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from testing-nestjs.