0
0
NestJSframework~20 mins

Integration testing in NestJS - Practice Problems & Coding Challenges

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