Exploring NestJs: A comprehensive guide to testing response controllers

I am looking to use Jest to test the responses from my API. This method is from my 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],
    })
  }

Here is the test I have written:

  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)
    })
  })

I encountered an error:

https://i.sstatic.net/Q64MB.png

Could anyone provide guidance on how I can mock the response?

Answer №1

To mock the response, you should do the following:

const mockStatusResponse = {
  send: jest.fn((data) => data),
}

const mockResponse = {
  status: jest.fn((code) => mockStatusResponse),
  send: jest.fn((data) => data),
} as unknown as Response

Answer №2

If you are utilizing foo.pipe(res), here is a custom class I created to test it:

class ResponseMock extends Writable {
    private responseText = '';

    public _write(
        chunk: string,
        encoding: BufferEncoding,
        callback: (error?: Error | null) => void
    ): void {
        this.responseText += chunk;
        callback();
    }

    /**
     * Retrieve the complete response when ready
     */
    public async getResponse(): Promise<string> {
        return await new Promise<string>((resolve): void => {
            this.on('finish', (): void => {
                resolve(this.responseText);
            });
        });
    }
}

This class can be utilized as follows:

import { Response } from 'express';

const responseMock = new ResponseMock();

await controller.query(
    param1,
    param2,
    responseMock as unknown as Response
);

await expect(responseMock.getResponse()).resolves.toEqual('foo');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Buffer Overflow - Security Audit - Node JS TypeScript Microservice Vulnerability Scan Report

Person Data Schema: import JoiBase from '@hapi/joi'; import JoiDate from '@hapi/joi-date'; const Joi = JoiBase.extend(JoiDate); const personDataSchema = Joi.object().keys({ person: Joi.object().keys({ personId: Joi.string().max( ...

ES6 Update: Manipulating Nested Arrays with JavaScript

I have the following list of items: [ { idItem: "1", name: "apple", itemLikes: [{ id: "1", idItem: "1" }] } ] My goal is to simply add a new object to the itemLikes array. Here is my ...

What is the best way to send JSON data from Express to a JavaScript/jQuery script within a Pug template?

Currently, I am facing a challenge in passing JSON data from an Express route to a .js file located within a .pug template. I have been attempting to solve this issue using the following method: The router: // Office Locations router.get('/office_lo ...

What is the best way to transfer an item to a router?

I've been developing an endpoint and I am trying to configure it to function similar to bot/:id/vote How can I retrieve the ID in order to pass it into the router so that it appears as https://example.com/bot/512333785338216465/vote Code const voting ...

Controlling the upper and lower limits in an input field for numerical values while manually typing in the text

Trying to implement an Angular component input with number type that allows setting a maximum and minimum value. Here is the code snippet used for calling the component in HTML: <app-input-number [(value)]="inputMinMaxValueNumber" [min]="min" [max]="m ...

Implementing Batch File Uploads using Typescript

Is there a way to upload multiple files in TypeScript without using React or Angular, but by utilizing an interface and getter and setter in a class? So far I have this for single file upload: <input name="myfile" type="file" multi ...

The attribute 'limitTags' is not present in the type 'IntrinsicAttributes & AutocompleteProps'

The Versions of Material UI and Lab I am Utilizing "@material-ui/core": "^4.8.3", "@material-ui/lab": "^4.0.0-alpha.44", Visit the component here Snippet of My Code <Autocomplete multiple limitTags={2} id="multiple-limit-tags" ...

What methods can be used to ensure the document in mongoose is not deleted by updating the expires property on the createdAt field?

I have implemented account verification in this app and created a user account that is set to delete itself after 30 seconds if not verified. createdAt: { type: Date, default: Date.now, index: { expires: 30, }, }, However, I am now searching f ...

Struggling with effectively executing chained and inner promises

It seems like my promises are not completing as expected due to incorrect handling. When using Promise.all(), the final result displayed with console.log(payload) is {}. Ideally, it should show something similar to this: { project1: { description: & ...

Steps for invoking an express.js handler from a different handler

Currently in the process of constructing an isomorphic React application that utilizes express.js on the server end. The client portion of the app sends a variety of AJAX requests to other express handlers, resulting in multiple HTTP calls to the same serv ...

Is it possible to rotate an image with a random angle when hovering in Angular?

I'm currently working on a photo gallery project and my goal is to have the images rotate when hovered over. However, I am experiencing difficulties in passing values from TypeScript into the CSS. HTML <div class="back"> <div cl ...

What is the best way to determine the cipher suites that a client has at their disposal?

Hello there! I am currently operating a Node server and am faced with the challenge of determining the cipher suites that a requesting client is able to support. Is it feasible to accomplish this in a single instance? ...

A step-by-step guide to configuring automated browser tests on Travis CI

I am currently in the process of setting up automated tests for my web application on Travis CI. Specifically, I am focusing on setting up automated browser tests, as running unit tests is straightforward. However, I require a process/system test that can ...

What is the best way to integrate @uirouter in the Angular/sampleapp project?

Having trouble configuring the angular/sampleapp to work with @uirouter. Is the systemjs.config.js file set up incorrectly to include @uirouter? 1) Run npm i -S @uirouter/angular 2) Add the following line to the map section in systemjs.config.js ' ...

Encountering a Typescript error with Next-Auth providers

I've been struggling to integrate Next-Auth with Typescript and an OAuth provider like Auth0. Despite following the documentation, I encountered a problem that persists even after watching numerous tutorials and mimicking their steps verbatim. Below i ...

Encountering TypeScript Error when Using Hooks (possible type mismatch?)

Currently, I am developing a custom `useProject` hook in TypeScript that is utilizing a function defined in `useProjectFunctions.ts`. While working on the `useProject` hook, I encountered a TypeScript error indicating type mismatch, although I am unable t ...

Exploring the world of tabbed dynamic routing in Angular 2 version 4

Today I encountered a routing issue that requires assistance from all of you. Currently, I have a sidebar with dynamic tree view navigations on the left and 4 tabs on the right. By default, tab1 is selected to display data related to the active link. Lin ...

Can an Angular Component be displayed using a Serverless function like Lambda on AWS?

I have a single-page application developed in JavaScript using the Angular 6 Framework, and I am interested in dynamically rendering an Angular Component that is hosted on a remote server. Currently, I am utilizing viewContainerRef to dynamically render ...

Include a control within a form based on the Observable response

I am looking to enhance my form by adding a control of array type, but I need to wait for the return of an Observable before mapping the values and integrating them into the form. The issue with the current code is that it inserts an empty array control e ...

Issue with playing audio file using HowlerJS

Having trouble playing a .mp3 file in my project directory with Howler. I'm not sure if there's an error in my src. When I tried playing an online hosted audio file, it worked fine. I've placed the audio file in the same directory as Slideon ...