0
0
NestjsHow-ToBeginner ยท 3 min read

How to Use Test Module in NestJS for Unit Testing

In NestJS, use the Test module from @nestjs/testing to create a testing module that mimics your app module. This allows you to instantiate providers and controllers in isolation for unit testing with Test.createTestingModule() and compile().
๐Ÿ“

Syntax

The Test module provides a method createTestingModule() which accepts a module metadata object similar to a regular NestJS module. After defining providers, controllers, and imports, call compile() to build the testing module. Then use get() to retrieve instances for testing.

  • createTestingModule({}): Defines the test module with providers, controllers, and imports.
  • compile(): Compiles the module and returns a TestingModule instance.
  • get(token): Retrieves an instance of a provider or controller from the compiled module.
typescript
const moduleRef = await Test.createTestingModule({
  providers: [MyService],
  controllers: [MyController],
  imports: [OtherModule],
}).compile();

const service = moduleRef.get<MyService>(MyService);
๐Ÿ’ป

Example

This example shows how to test a simple service using the Test module. It creates a testing module with the service provider, compiles it, and then tests a method.

typescript
import { Test, TestingModule } from '@nestjs/testing';
import { MyService } from './my.service';

describe('MyService', () => {
  let service: MyService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [MyService],
    }).compile();

    service = module.get<MyService>(MyService);
  });

  it('should return expected value', () => {
    expect(service.getHello()).toBe('Hello World!');
  });
});

// my.service.ts
export class MyService {
  getHello(): string {
    return 'Hello World!';
  }
}
Output
PASS MyService โœ“ should return expected value (5 ms)
โš ๏ธ

Common Pitfalls

Common mistakes when using the Test module include:

  • Not calling compile() before accessing providers, which causes errors.
  • Forgetting to include all required providers or imports, leading to undefined dependencies.
  • Trying to test asynchronous providers without using async/await properly.

Always ensure your test module mimics the real module dependencies needed for the test.

typescript
/* Wrong: Missing compile() call */
const moduleRef = Test.createTestingModule({
  providers: [MyService],
});
const service = moduleRef.get<MyService>(MyService); // Error: moduleRef is a Promise

/* Right: Use await and compile() */
const moduleRef = await Test.createTestingModule({
  providers: [MyService],
}).compile();
const service = moduleRef.get<MyService>(MyService);
๐Ÿ“Š

Quick Reference

Summary tips for using the NestJS Test module:

  • Always use await Test.createTestingModule(...).compile() to build the test module.
  • Include all necessary providers, controllers, and imports to avoid missing dependencies.
  • Use moduleRef.get() to retrieve instances for testing.
  • Use beforeEach to set up fresh module instances for isolated tests.
โœ…

Key Takeaways

Use Test.createTestingModule() with compile() to create isolated test modules.
Include all required providers and imports to avoid dependency errors.
Retrieve service or controller instances with moduleRef.get() for testing.
Always await compile() to ensure the module is ready before tests run.
Use beforeEach to reset the test environment for each test case.