Bird
Raised Fist0
NestJSframework~20 mins

Integration testing in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
NestJS Integration 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 integration test?
Consider this NestJS integration test snippet. What will be the test result output?
NestJS
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from '../src/app.module';

describe('AppController (integration)', () => {
  let app: INestApplication;

  beforeAll(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
  });

  it('/GET hello', () => {
    return request(app.getHttpServer())
      .get('/hello')
      .expect(200)
      .expect('Hello World!');
  });

  afterAll(async () => {
    await app.close();
  });
});
AThe test passes with status 200 and response 'Hello World!'
BThe test fails with status 404 because the route '/hello' does not exist
CThe test throws a runtime error because app.init() is missing
DThe test fails with status 500 due to missing controller
Attempts:
2 left
💡 Hint
Check the route and response expected in the test.
❓ lifecycle
intermediate
2:00remaining
What happens if you omit app.close() in NestJS integration tests?
In a NestJS integration test, what is the effect of not calling app.close() in afterAll?
NestJS
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from '../src/app.module';

describe('AppController (integration)', () => {
  let app: INestApplication;

  beforeAll(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
  });

  it('/GET hello', () => {
    return request(app.getHttpServer())
      .get('/hello')
      .expect(200)
      .expect('Hello World!');
  });

  // afterAll(async () => {
  //   await app.close();
  // });
});
AThe test will fail immediately with an error about unclosed resources
BThe test suite may hang or not exit because the server is still running
CThere is no effect; the test exits normally
DThe test will throw a syntax error due to missing app.close()
Attempts:
2 left
💡 Hint
Think about what happens to the server after tests finish.
🔧 Debug
advanced
2:00remaining
Why does this NestJS integration test fail with a 404 error?
This integration test returns 404 instead of 200. What is the cause?
NestJS
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from '../src/app.module';

describe('AppController (integration)', () => {
  let app: INestApplication;

  beforeAll(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      // Missing imports here
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
  });

  it('/GET hello', () => {
    return request(app.getHttpServer())
      .get('/hello')
      .expect(200)
      .expect('Hello World!');
  });

  afterAll(async () => {
    await app.close();
  });
});
Aapp.init() was not awaited, so the server is not ready
BThe test uses supertest incorrectly by missing await
CThe test expects wrong response text
DAppModule was not imported in the testing module, so the route is undefined
Attempts:
2 left
💡 Hint
Check what modules are included in the test setup.
📝 Syntax
advanced
2:00remaining
Which option correctly mocks a service in NestJS integration test?
You want to mock a service in your NestJS integration test. Which code snippet correctly overrides the service?
NestJS
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from '../src/app.module';
import { CatsService } from '../src/cats/cats.service';

const mockCatsService = {
  findAll: () => [{ name: 'MockCat' }],
};

describe('CatsController (integration)', () => {
  let app: INestApplication;

  beforeAll(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    })
    // ???
    .compile();

    app = moduleFixture.createNestApplication();
    await app.init();
  });

  it('/GET cats', () => {
    return request(app.getHttpServer())
      .get('/cats')
      .expect(200)
      .expect([{ name: 'MockCat' }]);
  });

  afterAll(async () => {
    await app.close();
  });
});
A.overrideProvider(CatsService).useValue(mockCatsService)
B.overrideService(CatsService).useValue(mockCatsService)
C.overrideProvider('CatsService').useValue(mockCatsService)
D.override(CatsService).useValue(mockCatsService)
Attempts:
2 left
💡 Hint
Check the official NestJS method to override providers in tests.
❓ state_output
expert
3:00remaining
What is the value of 'count' after this NestJS integration test runs?
Given this controller and integration test, what is the final value of 'count' in the service after the test?
NestJS
import { Injectable, Controller, Get } from '@nestjs/common';

@Injectable()
export class CounterService {
  count = 0;
  increment() {
    this.count++;
  }
  getCount() {
    return this.count;
  }
}

@Controller('counter')
export class CounterController {
  constructor(private readonly counterService: CounterService) {}

  @Get('inc')
  increment() {
    this.counterService.increment();
    return 'Incremented';
  }

  @Get('value')
  getValue() {
    return this.counterService.getCount();
  }
}

// Integration test snippet
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';

describe('CounterController (integration)', () => {
  let app: INestApplication;
  let counterService: CounterService;

  beforeAll(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      controllers: [CounterController],
      providers: [CounterService],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();

    counterService = moduleFixture.get<CounterService>(CounterService);
  });

  it('increments count', async () => {
    await request(app.getHttpServer()).get('/counter/inc').expect(200);
    await request(app.getHttpServer()).get('/counter/inc').expect(200);
  });

  it('gets count value', async () => {
    const res = await request(app.getHttpServer()).get('/counter/value').expect(200);
    expect(res.body).toBe(2);
  });

  afterAll(async () => {
    await app.close();
  });
});
A0
B1
C2
DUndefined because service is recreated each request
Attempts:
2 left
💡 Hint
Consider the service instance lifecycle during the test.

Practice

(1/5)
1. What is the main purpose of integration testing in NestJS?
easy
A. To test individual functions in isolation
B. To check how different parts of the application work together
C. To measure application performance under load
D. To check the syntax of TypeScript code

Solution

  1. Step 1: Understand integration testing goal

    Integration testing focuses on verifying that multiple parts of the app interact correctly.
  2. Step 2: Differentiate from other test types

    Unit tests check single functions; performance tests measure speed; syntax checks are done by compilers.
  3. Final Answer:

    To check how different parts of the application work together -> Option B
  4. Quick Check:

    Integration testing = check parts working together [OK]
Hint: Integration tests check combined parts, not single functions [OK]
Common Mistakes:
  • Confusing integration with unit testing
  • Thinking integration tests check performance
  • Believing integration tests check code syntax
2. Which of the following is the correct way to initialize a NestJS application for integration testing?
easy
A. const app = await Test.createTestingModule({ imports: [AppModule] }).start();
B. const app = new AppModule(); app.start();
C. const app = await Test.createTestingModule({ controllers: [AppController] }).init();
D. const app = (await Test.createTestingModule({ imports: [AppModule] }).compile()).createNestApplication(); await app.init();

Solution

  1. Step 1: Recognize correct testing module setup

    Use Test.createTestingModule with imports and then compile() to build the module.
  2. Step 2: Create app instance and initialize

    After compiling, create the app with createNestApplication() then call app.init() to start the NestJS app for testing.
  3. Final Answer:

    const app = (await Test.createTestingModule({ imports: [AppModule] }).compile()).createNestApplication(); await app.init(); -> Option D
  4. Quick Check:

    compile() -> createNestApplication() -> init() [OK]
Hint: Always compile() -> createNestApplication() -> init() [OK]
Common Mistakes:
  • Calling init() directly on createTestingModule
  • Using start() method which does not exist
  • Not compiling the testing module before init
3. Given this test snippet, what will be the HTTP status code returned?
const response = await request(app.getHttpServer()).get('/users');
expect(response.status).toBe(200);
medium
A. 200
B. 401
C. 500
D. 404

Solution

  1. Step 1: Understand the test request

    The test sends a GET request to '/users' route using supertest on the initialized app.
  2. Step 2: Check expected status code

    The test expects the response status to be 200, meaning success and route exists.
  3. Final Answer:

    200 -> Option A
  4. Quick Check:

    GET /users returns 200 success [OK]
Hint: 200 means route responded successfully [OK]
Common Mistakes:
  • Confusing 404 (not found) with 200
  • Assuming 500 error without error in code
  • Mixing authentication errors with route success
4. You wrote this integration test but it fails with "Cannot read property 'getHttpServer' of undefined". What is the likely cause?
let app;
beforeAll(async () => {
  app = Test.createTestingModule({ imports: [AppModule] });
  await app.init();
});
medium
A. Forgot to call compile() before init()
B. Used beforeAll instead of beforeEach
C. Did not import supertest library
D. AppModule is missing from imports

Solution

  1. Step 1: Identify missing compile() call

    Test.createTestingModule returns a builder; you must call compile() to get the module instance.
  2. Step 2: Understand why getHttpServer is undefined

    Without compile(), app is not a proper module instance, so app.getHttpServer is undefined causing the error.
  3. Final Answer:

    Forgot to call compile() before init() -> Option A
  4. Quick Check:

    compile() needed before init() [OK]
Hint: Always compile() before init() to get app instance [OK]
Common Mistakes:
  • Skipping compile() step
  • Confusing beforeAll with beforeEach for setup
  • Assuming missing imports cause this error
5. You want to test a POST route that creates a user. Which approach correctly integrates NestJS and supertest for this integration test?
hard
A. Use Jest mocks to simulate the database and skip app initialization
B. Directly call the controller method without app initialization and check returned value
C. Use Test.createTestingModule with AppModule, compile and init app, then use supertest to POST JSON to '/users' endpoint
D. Write a unit test for the service method that creates users

Solution

  1. Step 1: Setup full app for integration test

    Integration tests require the full app context, so createTestingModule with AppModule, compile, and init the app.
  2. Step 2: Use supertest to send POST request

    Use supertest to send a POST request with JSON data to the '/users' route to test real HTTP behavior.
  3. Final Answer:

    Use Test.createTestingModule with AppModule, compile and init app, then use supertest to POST JSON to '/users' endpoint -> Option C
  4. Quick Check:

    Integration test = full app + supertest POST [OK]
Hint: Integration tests use full app and supertest for HTTP calls [OK]
Common Mistakes:
  • Testing controller methods directly without app context
  • Using mocks instead of real modules for integration tests
  • Confusing unit tests with integration 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