0
0
NestjsHow-ToBeginner ยท 3 min read

How to Test Service in NestJS: Simple Guide with Examples

To test a service in NestJS, use TestingModule from @nestjs/testing to create a test module and get the service instance. Then write unit tests with Jest to check service methods by calling them and asserting expected results.
๐Ÿ“

Syntax

Use Test.createTestingModule to build a testing module that includes the service. Then call compile() to prepare it. Use module.get() to get the service instance for testing.

Write test cases with describe and it blocks from Jest to organize and run tests.

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 be defined', () => {
    expect(service).toBeDefined();
  });

  // Add more tests here
});
๐Ÿ’ป

Example

This example shows how to test a simple service method that adds two numbers. It creates a test module, gets the service, and checks the method's output.

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

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

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

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

  it('should add two numbers correctly', () => {
    const result = service.add(2, 3);
    expect(result).toBe(5);
  });
});

// calculator.service.ts
export class CalculatorService {
  add(a: number, b: number): number {
    return a + b;
  }
}
Output
PASS ./calculator.service.spec.ts CalculatorService โœ“ should add two numbers correctly (5 ms) Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 1.234 s
โš ๏ธ

Common Pitfalls

  • Not importing or providing dependencies the service needs causes errors.
  • Forgetting to call compile() on the testing module will prevent service instantiation.
  • Testing asynchronous methods without async/await or proper mocks leads to flaky tests.
  • Not isolating the service by mocking external dependencies can cause tests to fail unpredictably.
typescript
/* Wrong: Missing compile() call */
const module = Test.createTestingModule({ providers: [MyService] });
const service = module.get(MyService); // Error: module not compiled

/* Right: Call compile() and await it */
const module = await Test.createTestingModule({ providers: [MyService] }).compile();
const service = module.get(MyService);
๐Ÿ“Š

Quick Reference

Remember these steps to test a NestJS service:

  • Use Test.createTestingModule with providers array including your service.
  • Call compile() and await it.
  • Get the service instance with module.get().
  • Write tests using Jest's describe and it.
  • Mock dependencies if your service uses other services or modules.
โœ…

Key Takeaways

Use TestingModule from @nestjs/testing to create and compile a test module with your service.
Get the service instance from the compiled module before running tests.
Write unit tests with Jest to call service methods and check expected results.
Always mock dependencies to isolate the service under test.
Remember to await compile() to properly initialize the testing module.