Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

1.4K
Vistas
Unit testing NestJS controller with request

My Controller function definition looks like that: async login(@Req() request, @Body() loginDto: LoginDto): Promise<any> {

How I could prepare/mockup Request to provide first argument of function from Jest test? Inside funciton I am setting headers using request.res.set. Should I somehow pass real Request object to function and then check if header is set or rather mockup whole Request object and check if set function was called?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

I managed to do that mocking requests and response using node-mocks-http library.

const req = mocks.createRequest() req.res = mocks.createResponse()

and then passing this as an argument.

const data = await authController.login(req, loginDto) expect(req.res.get('AccessToken')).toBe(token.accessToken)

over 4 years ago · Santiago Trujillo Denunciar

0

I followed a different approach and instead of using node-mocks-http library I used @golevelup/ts-jest, also, instead of testing if the function returns some value, like res.json() or res.status(), I checked if the function was called with the value I wanted to.

I borrowed this approach from Kent C. Dodds's testing workshop, take a look for similar ideas. Anyway, this is what I did in order to mock the Response dependency of my Controller's route:

  // cars.controller.spec.ts
  import { createMock } from '@golevelup/ts-jest';

  const mockResponseObject = () => {
    return createMock<Response>({
      json: jest.fn().mockReturnThis(),
      status: jest.fn().mockReturnThis(),
    });
  };


  ... ommited for brevity

  it('should return an array of Cars', async () => {
    const response = mockResponseObject();

    jest
      .spyOn(carsService, 'findAll')
      .mockImplementation(jest.fn().mockResolvedValueOnce(mockedCarsList));

    await carsController.getCars(response);

    expect(response.json).toHaveBeenCalledTimes(1);
    expect(response.json).toHaveBeenCalledWith({ cars: mockedCarsList });
    expect(response.status).toHaveBeenCalledTimes(1);
    expect(response.status).toHaveBeenCalledWith(200);
  });

And that's it, I think that the implementation details aren't that important but in any case I'll leave the link to the Github repo where you can find the whole project.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda