Bird
Raised Fist0
NestJSframework~20 mins

Testing module setup in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
NestJS 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 testing module setup?
Consider this NestJS test setup code. What will be the value of service.getHello() after the test module is compiled and the service is retrieved?
NestJS
import { Test, TestingModule } from '@nestjs/testing';
import { AppService } from './app.service';

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

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

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

  it('should return greeting', () => {
    expect(service.getHello()).toBe('Hello World!');
  });
});
A'Hello NestJS!'
B'Hello World!'
Cundefined
DThrows an error because service is not defined
Attempts:
2 left
💡 Hint
Look at how the service is provided and retrieved from the testing module.
📝 Syntax
intermediate
2:00remaining
Which option causes a syntax error in NestJS testing module setup?
Identify which code snippet will cause a syntax error when setting up a NestJS testing module.
NestJS
import { Test, TestingModule } from '@nestjs/testing';

async function setup() {
  const module = await Test.createTestingModule({
    providers: [
      {
        provide: 'MyService',
        useClass: MyService,
      }
    ]
  }).compile();
  return module;
}
AMissing comma after useClass: MyService
BUsing useValue with an object literal
CProviding a string token without useClass or useValue
DUsing useClass without quotes around MyService
Attempts:
2 left
💡 Hint
Check the commas between object properties carefully.
🔧 Debug
advanced
3:00remaining
Why does this NestJS test fail with 'Nest can't resolve dependencies' error?
Given this testing module setup, why does the test fail with a dependency resolution error?
NestJS
import { Test, TestingModule } from '@nestjs/testing';
import { AppService } from './app.service';
import { AppController } from './app.controller';

describe('AppController', () => {
  let controller: AppController;

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

    controller = module.get<AppController>(AppController);
  });

  it('should return greeting', () => {
    expect(controller.getHello()).toBe('Hello World!');
  });
});
AAppService is not provided in the testing module providers array
BAppController is not declared in controllers array
CMissing async keyword in beforeEach
DIncorrect import path for AppController
Attempts:
2 left
💡 Hint
Check what dependencies AppController needs and if they are provided.
❓ state_output
advanced
2:30remaining
What is the value of 'result' after this NestJS test runs?
In this test, what will be the value of the variable result after calling service.getData()?
NestJS
import { Test, TestingModule } from '@nestjs/testing';
import { DataService } from './data.service';

class MockDataService {
  getData() {
    return ['mock1', 'mock2'];
  }
}

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

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

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

  it('should return mocked data', () => {
    const result = service.getData();
    expect(result).toEqual(['mock1', 'mock2']);
  });
});
A['real1', 'real2']
B[]
CThrows error because of duplicate providers
D['mock1', 'mock2']
Attempts:
2 left
💡 Hint
Check which provider is used when multiple providers for the same token exist.
🧠 Conceptual
expert
2:00remaining
Which option best describes the purpose of NestJS TestingModule's compile() method?
What does the compile() method do when called on a NestJS TestingModule builder?
AIt compiles TypeScript code to JavaScript for the module
BIt runs all tests defined in the module automatically
CIt creates an instance of the module and resolves all dependencies for testing
DIt resets the module to its initial state before each test
Attempts:
2 left
💡 Hint
Think about what is needed before you can use the module's providers and controllers in tests.

Practice

(1/5)
1. What is the main purpose of using Test.createTestingModule() in NestJS testing?
easy
A. To create a small test version of your app module with needed parts
B. To start the full application server for integration testing
C. To generate database seed data automatically
D. To deploy the app to production environment

Solution

  1. Step 1: Understand the role of Test.createTestingModule()

    This method creates a lightweight module for testing, including only what you add (controllers, providers, imports).
  2. Step 2: Compare with other options

    Starting the full app server or deploying is not the purpose of this method. It is only for isolated testing setup.
  3. Final Answer:

    To create a small test version of your app module with needed parts -> Option A
  4. Quick Check:

    Testing module setup = small test module [OK]
Hint: Testing module creates mini app for safe isolated tests [OK]
Common Mistakes:
  • Thinking it starts the full app server
  • Confusing with deployment or seeding
  • Assuming it runs tests automatically
2. Which of the following is the correct way to compile a testing module in NestJS?
easy
A. await compileTestingModule(Test.createTestingModule({}));
B. Test.createTestingModule({}).compile();
C. Test.compileTestingModule({});
D. await Test.createTestingModule({}).compile();

Solution

  1. Step 1: Recall the async nature of compile()

    The compile() method returns a Promise, so it must be awaited.
  2. Step 2: Check syntax correctness

    Only await Test.createTestingModule({}).compile(); correctly uses await with Test.createTestingModule({}).compile(). Others are either missing await or use invalid methods.
  3. Final Answer:

    await Test.createTestingModule({}).compile(); -> Option D
  4. Quick Check:

    Compile returns Promise, so use await [OK]
Hint: Always await compile() on testing module [OK]
Common Mistakes:
  • Forgetting to await compile()
  • Using non-existent compileTestingModule method
  • Calling compile without parentheses
3. Given this test setup code snippet, what will service.getData() return?
const moduleRef = await Test.createTestingModule({
  providers: [{
    provide: 'DataService',
    useValue: { getData: () => 'mocked data' },
  }],
}).compile();
const service = moduleRef.get('DataService');
return service.getData();
medium
A. Throws runtime error
B. undefined
C. 'mocked data'
D. 'real data'

Solution

  1. Step 1: Identify the provider mock

    The provider 'DataService' is mocked with an object whose getData method returns 'mocked data'.
  2. Step 2: Understand the get call

    Calling moduleRef.get('DataService') returns the mocked object, so service.getData() returns 'mocked data'.
  3. Final Answer:

    'mocked data' -> Option C
  4. Quick Check:

    Mock provider method returns 'mocked data' [OK]
Hint: Mocked provider returns its defined value [OK]
Common Mistakes:
  • Expecting real data instead of mock
  • Assuming get returns undefined without provider
  • Confusing provider token with class
4. What is wrong with this NestJS testing module setup?
const moduleRef = await Test.createTestingModule({
  controllers: [AppController],
  providers: [AppService],
});
const controller = moduleRef.get(AppController);
medium
A. Controllers should not be added in testing modules
B. Missing call to compile() before getting controller
C. Providers array should be empty
D. Cannot get controller by class reference

Solution

  1. Step 1: Check testing module lifecycle

    After creating the testing module, you must call compile() to finalize it before retrieving instances.
  2. Step 2: Identify missing compile call

    The code does not call await moduleRef.compile(), so moduleRef.get() will fail or behave unexpectedly.
  3. Final Answer:

    Missing call to compile() before getting controller -> Option B
  4. Quick Check:

    Always compile testing module before get() [OK]
Hint: Always await compile() before accessing module instances [OK]
Common Mistakes:
  • Forgetting to compile testing module
  • Thinking controllers can't be added
  • Trying to get by string token instead of class
5. You want to test a service that depends on another service. How do you set up the testing module to replace the dependency with a mock implementation?
hard
A. Add the service and provide a mock using useValue for the dependency in providers array
B. Only add the main service, NestJS auto-mocks dependencies
C. Add both services without mocks, real implementations are always used
D. Use imports to load the dependency module instead of mocking

Solution

  1. Step 1: Understand dependency injection in testing

    To replace a dependency, you provide a mock object using useValue in the providers array.
  2. Step 2: Setup providers correctly

    Add the main service normally and add the dependency with provide and useValue to inject the mock.
  3. Final Answer:

    Add the service and provide a mock using useValue for the dependency in providers array -> Option A
  4. Quick Check:

    Mock dependencies with useValue in providers [OK]
Hint: Mock dependencies by providing useValue in providers [OK]
Common Mistakes:
  • Assuming NestJS auto-mocks dependencies
  • Not providing mock for dependency
  • Using imports instead of mocking for isolated tests
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