0
0
NestJSframework~20 mins

Unit testing services in NestJS - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
NestJS Unit Testing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this NestJS service unit test?
Consider this simple NestJS service and its unit test. What will the test output be when run?
NestJS
import { Injectable } from '@nestjs/common';

@Injectable()
export class MathService {
  double(value: number): number {
    return value * 2;
  }
}

// Test file
import { Test, TestingModule } from '@nestjs/testing';
import { MathService } from './math.service';

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

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

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

  it('should return double the input', () => {
    expect(service.double(4)).toBe(8);
  });
});
AThe test throws a runtime error due to missing dependencies.
BThe test fails because the service is not mocked.
CThe test fails because the expected value is incorrect.
DThe test passes successfully.
Attempts:
2 left
💡 Hint
Think about how the service is provided and used in the test module.
🔧 Debug
intermediate
2:00remaining
Why does this NestJS service unit test fail with a TypeError?
Look at this unit test for a NestJS service. Why does it fail with a TypeError: Cannot read property 'getData' of undefined?
NestJS
import { Injectable } from '@nestjs/common';

@Injectable()
export class DataService {
  getData(): string {
    return 'data';
  }
}

// Test file
import { Test, TestingModule } from '@nestjs/testing';
import { DataService } from './data.service';

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

  beforeEach(() => {
    service = new DataService();
  });

  it('should return data string', () => {
    expect(service.getData()).toBe('data');
  });

  it('should call getData method', () => {
    const spy = jest.spyOn(service, 'getData');
    service.getData();
    expect(spy).toHaveBeenCalled();
  });
});
AThe spy is created after the method call, so it never detects the call.
BThe service instance is created manually, so jest.spyOn cannot spy on it properly.
CThe service is not injected via TestingModule, so dependencies are missing causing the error.
DThe service method getData is not defined, causing the TypeError.
Attempts:
2 left
💡 Hint
Check the order of spy creation and method call.
📝 Syntax
advanced
2:00remaining
Which option correctly mocks a dependency in a NestJS service unit test?
You have a NestJS service that depends on another service. Which test setup correctly mocks the dependency?
NestJS
import { Injectable } from '@nestjs/common';

@Injectable()
export class UserService {
  constructor(private readonly authService: AuthService) {}

  isUserAuthenticated(userId: string): boolean {
    return this.authService.validateUser(userId);
  }
}

// AuthService interface
export class AuthService {
  validateUser(userId: string): boolean {
    return true;
  }
}

// Test file snippet
import { Test, TestingModule } from '@nestjs/testing';
import { UserService } from './user.service';
import { AuthService } from './auth.service';
Aproviders: [UserService, { provide: AuthService, useClass: AuthService }]
Bproviders: [UserService, { provide: AuthService, useValue: { validateUser: () => true } }]
Cproviders: [UserService, { provide: AuthService, useFactory: () => ({ validateUser: () => true }) }]
Dproviders: [UserService, { provide: AuthService, useValue: { validateUser: () => false } }]
Attempts:
2 left
💡 Hint
Mocking with useValue allows you to replace methods with your own implementations.
state_output
advanced
2:00remaining
What is the value of 'result' after this NestJS service test runs?
Given this service and test, what will be the value of the variable 'result' after the test runs?
NestJS
import { Injectable } from '@nestjs/common';

@Injectable()
export class CounterService {
  private count = 0;

  increment(): number {
    return ++this.count;
  }

  reset(): void {
    this.count = 0;
  }
}

// Test file
import { Test, TestingModule } from '@nestjs/testing';
import { CounterService } from './counter.service';

describe('CounterService', () => {
  let service: CounterService;
  let result: number;

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

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

  it('increments and resets count', () => {
    service.increment();
    service.increment();
    service.reset();
    result = service.increment();
  });
});
A2
B3
C1
D0
Attempts:
2 left
💡 Hint
Think about how the reset method affects the count before the last increment.
🧠 Conceptual
expert
2:00remaining
Which statement best describes the role of TestingModule in NestJS unit tests?
In NestJS unit testing, what is the main purpose of using the TestingModule?
AIt creates a lightweight module to provide and inject dependencies for isolated testing of components or services.
BIt automatically mocks all dependencies of a service without manual configuration.
CIt replaces the need for Jest or other testing frameworks by handling assertions internally.
DIt compiles the entire application to run integration tests with real database connections.
Attempts:
2 left
💡 Hint
Think about how NestJS manages dependencies during tests.