NestJs how to test response controller

Issue

I would like to test with jest the responses for my API.

this is method from controller

  @Post('send-banana')
  async sendBanana(
    @Body() request: BananaRequest,
    @Res() res: Response,
  ) {
    const responseCodeService = await this.bananaService.sendBanana(
      request,
    )

    res.status(responseCodeService).send({
      code: responseCodeService,
      message: HttpStatus[responseCodeService],
    })
  }

this is the test

  describe('Banana Controller', () => {
    fit('should return httpcode(201)', async () => {
      const result = await Promise['']

      const request = {
        origin: 'dummy origin',
        receiver: '[email protected]',
        data: {
          name: 'Elsa Pallo',
        },
      } as BananaRequest

      const response = jest.fn((resObj) => ({
        status: jest.fn((status) => ({
          res: { ...resObj, statusCode: status },
        })),
      }))

      jest
        .spyOn(bananaService, 'sendBanana')
        .mockImplementation(() => result)

      expect(
        await bananaController.sendBanana(request, response),
      ).toBe(result)
    })
  })

This is the error that I get

enter image description here

Can someone guide me how I can mock the response?

Solution

You need mock the response as follows:

const statusResponseMock = {
        send: jest.fn((x) => x),
      }
    
      const responseMock = {
        status: jest.fn((x) => statusResponseMock),
        send: jest.fn((x) => x),
      } as unknown as Response

Answered By – David Berríos

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published