Home > OS >  NestJs how to test response controller
NestJs how to test response controller

Time:08-03

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: 'dummy@dummy',
        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?

CodePudding user response:

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
  • Related