0
0
NestJSframework~10 mins

Unit testing controllers in NestJS - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the testing module for a NestJS controller test.

NestJS
import { Test, TestingModule } from '@nestjs/[1]';
Drag options to blanks, or click blank then click option'
Acore
Bcommon
Ctesting
Dplatform-express
Attempts:
3 left
💡 Hint
Common Mistakes
Importing from '@nestjs/common' instead of '@nestjs/testing'.
Using '@nestjs/core' which is for core framework features.
2fill in blank
medium

Complete the code to create a testing module for the controller named 'CatsController'.

NestJS
const moduleRef: TestingModule = await Test.createTestingModule({ controllers: [[1]] }).compile();
Drag options to blanks, or click blank then click option'
ACatsController
BDogsController
CBirdsController
DFishController
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different controller name than the one being tested.
Forgetting to include the controller in the testing module.
3fill in blank
hard

Fix the error in retrieving the controller instance from the testing module.

NestJS
const controller = moduleRef.[1](CatsController);
Drag options to blanks, or click blank then click option'
Aget
BgetController
Cretrieve
Dfetch
Attempts:
3 left
💡 Hint
Common Mistakes
Using non-existent methods like 'getController' or 'fetch'.
Trying to access the controller directly without using 'get'.
4fill in blank
hard

Fill both blanks to mock a service method and test the controller's response.

NestJS
jest.spyOn(service, '[1]').mockImplementation(() => [2]);
Drag options to blanks, or click blank then click option'
AfindAll
B[{ id: 1, name: 'Fluffy' }]
Creturn 'Hello'
Dcreate
Attempts:
3 left
💡 Hint
Common Mistakes
Mocking the wrong method name.
Returning a wrong type like a string instead of an array.
5fill in blank
hard

Fill all three blanks to write a test that checks if the controller's getAll method returns the mocked data.

NestJS
it('should return an array of cats', async () => {
  const result = await controller.[1]();
  expect(result).toEqual([2]);
  expect(service.[3]).toHaveBeenCalled();
});
Drag options to blanks, or click blank then click option'
AgetAll
B[{ id: 1, name: 'Fluffy' }]
CfindAll
Dcreate
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong method names in controller or service.
Not matching the expected data with the mocked return.