Menu

Write your Nest.js 12 tests as decorated classes with Mocha
📰

Write your Nest.js 12 tests as decorated classes with Mocha

DEV Community: typescript·Maximiliano Ezequiel Carrizo·18 days ago
#cL3Nkh2B
#devtotypescript#devto#dev#test#mocha
Reading 0:00
15s threshold

Nest.js applications are built from classes, decorators and dependency injection. Tests usually aren't: they are anonymous functions that fetch what they need with app.get(Component) .

nestjs-mocha-decorators lets you write tests the same way you write the rest of your app. Suites and tests are plain classes and methods, and test classes are Nest providers.

@ TestSuite ( ' Demo Test Suite ' ) export class DemoTest { @ Inject () private readonly httpService ! : HttpService ;

@ Test ( ' Get Test ' ) async testGet (): Promise < void > { const { data } = await firstValueFrom ( this . httpService . get ( ' http://localhost:4343/demo ' )); expect ( data ). toBe ( ' Hello, Test world ! ' ); } }

Enter fullscreen mode

Exit fullscreen mode

@TestSuite is a Mocha describe , @Test is a Mocha it , and @Inject() works as it does anywhere else in Nest.

Installation

You need Nest.js 12, Mocha 12 and Node.js ^20.19.0 or >=22.12.0 .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.