Bird
Raised Fist0
NestJSframework~20 mins

Unit testing services in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of unit testing a service in NestJS?
easy
A. To verify the service works correctly on its own without dependencies
B. To test the entire application including all modules
C. To check the UI components connected to the service
D. To deploy the service to production automatically

Solution

  1. Step 1: Understand unit testing scope

    Unit testing focuses on testing a single piece of code in isolation, here the service alone.
  2. Step 2: Identify what unit testing excludes

    It excludes integration with other modules or UI, focusing only on the service logic.
  3. Final Answer:

    To verify the service works correctly on its own without dependencies -> Option A
  4. Quick Check:

    Unit testing = isolated service check [OK]
Hint: Unit test means testing one piece alone, no dependencies [OK]
Common Mistakes:
  • Confusing unit test with integration test
  • Thinking unit test covers UI or deployment
  • Assuming unit test runs the whole app
2. Which of the following is the correct way to get a service instance in a NestJS unit test?
easy
A. const service = require('MyService');
B. const service = new MyService();
C. const service = module.get<MyService>(MyService);
D. const service = app.getService(MyService);

Solution

  1. Step 1: Use NestJS TestingModule

    In unit tests, you create a TestingModule and get the service instance via module.get.
  2. Step 2: Identify correct syntax

    The syntax module.get<MyService>(MyService) is the official way to retrieve the service from the test module.
  3. Final Answer:

    const service = module.get<MyService>(MyService); -> Option C
  4. Quick Check:

    Use module.get to get service instance [OK]
Hint: Always get service from TestingModule with module.get<Type>(Type) [OK]
Common Mistakes:
  • Instantiating service directly without module
  • Using app.getService which is not a NestJS method
  • Using require which is not for NestJS DI
3. Given this test code snippet, what will be the output of service.getData()?
const mockData = ['a', 'b'];
const mockRepo = { findAll: () => mockData };

const module = await Test.createTestingModule({
  providers: [
    MyService,
    { provide: MyRepository, useValue: mockRepo },
  ],
}).compile();

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

console.log(service.getData());
medium
A. An error because MyRepository is not mocked
B. undefined
C. [] (empty array)
D. ['a', 'b']

Solution

  1. Step 1: Understand mocking of MyRepository

    The mockRepo object replaces MyRepository with a findAll method returning ['a', 'b'].
  2. Step 2: Analyze service.getData()

    Assuming getData calls repository.findAll(), it will return ['a', 'b'] from the mock.
  3. Final Answer:

    ['a', 'b'] -> Option D
  4. Quick Check:

    Mocked repo returns ['a', 'b'] so service returns same [OK]
Hint: Mocked methods return mock values used by service [OK]
Common Mistakes:
  • Forgetting to mock repository causing undefined
  • Expecting real database call instead of mock
  • Assuming empty array without mock data
4. What is the main issue in this test setup code?
const module = await Test.createTestingModule({
  providers: [MyService],
}).compile();

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

jest.spyOn(service, 'findAll').mockReturnValue(['x', 'y']);
medium
A. You cannot spy on service methods before mocking dependencies
B. The service method findAll should be mocked on the dependency, not service
C. jest.spyOn syntax is incorrect here
D. Missing async keyword on test function

Solution

  1. Step 1: Identify what to mock in unit tests

    In unit tests, you mock dependencies of the service, not the service's own methods.
  2. Step 2: Understand why mocking service method is wrong

    Mocking service.findAll replaces the method under test, defeating the purpose of testing it.
  3. Final Answer:

    The service method findAll should be mocked on the dependency, not service -> Option B
  4. Quick Check:

    Mock dependencies, not the service itself [OK]
Hint: Mock dependencies, never the service method you test [OK]
Common Mistakes:
  • Mocking the service method instead of its dependencies
  • Confusing spyOn usage with mocking dependencies
  • Ignoring async test function requirements
5. You want to test a service method that calls two different repository methods internally. How should you set up your unit test to isolate the service logic correctly?
hard
A. Mock both repository methods with expected return values and inject them into the test module
B. Call the real repository methods to test the full flow
C. Mock only one repository method and leave the other real
D. Do not mock anything and test the service directly

Solution

  1. Step 1: Identify dependencies to mock

    Since the service calls two repository methods, both should be mocked to isolate service logic.
  2. Step 2: Setup test module with mocks

    Provide mock implementations for both methods in the test module providers to control their outputs.
  3. Step 3: Avoid real calls in unit tests

    Calling real repository methods would make it an integration test, not a unit test.
  4. Final Answer:

    Mock both repository methods with expected return values and inject them into the test module -> Option A
  5. Quick Check:

    Mock all dependencies to isolate service logic [OK]
Hint: Mock all called dependencies to isolate service logic [OK]
Common Mistakes:
  • Mocking only some dependencies causing partial isolation
  • Calling real methods making it integration test
  • Not injecting mocks properly into test module
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard