NestJS 11 cheatsheet

NestJS 11: Testing

4 common NestJS 11 tasks.

Unit test a service

Build a small testing module with only what the test needs.

const moduleRef = await Test.createTestingModule({
  providers: [CatsService],
}).compile();
const service = moduleRef.get(CatsService);
expect(service.findAll()).toEqual([]);

Replace a dependency with a fake

Provide a mock in place of the real provider.

const moduleRef = await Test.createTestingModule({
  controllers: [CatsController],
  providers: [{ provide: CatsService, useValue: { findAll: () => ['cat'] } }],
}).compile();

Test over HTTP

Start the app in memory and call it with supertest.

const app = moduleRef.createNestApplication();
await app.init();
await request(app.getHttpServer()).get('/cats').expect(200);

Run the tests

Run unit tests, e2e tests and coverage.

npm run test
npm run test:e2e
npm run test:cov

Was this page helpful?