The POST requests on Next JS Mock API endpoints include parameters passed in the req.body

I am currently running Next JS API tests using jest with a custom testClient. The code for the testClient is as follows:

import { createServer } from 'http';

import type { NextApiHandler } from 'next';
import type { __ApiPreviewProps } from 'next/dist/next-server/server/api-utils';
import { apiResolver } from 'next/dist/next-server/server/api-utils';
import request from 'supertest';

export default (handler: NextApiHandler, query: Record<string, unknown> | undefined): request.SuperTest<request.Test> =>
  request(
    createServer(async (req, res) => {
      return apiResolver(req, res, query, handler, {} as __ApiPreviewProps, false);
    }),
  );

In my test files, I have the following code:


import myEndpoint from '../myEndpoint';

describe('test endpoint', () => {
  test('verify log event endpoint fails on get request', async () => {
    expect.assertions(2);
    const client = testClient(myEndpoint, {param: 'testValue'}, false);
    const response = await client.post(‘/‘);
    expect(response.status).toBe(200);
    expect(response.body.success).toBe(false);
  });

The myEndpoint function looks like this:

export default async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
   if (req.method !== 'POST') {
     res.json({ success: false });
     return;
   }

   // use req.body.param

However, I encountered an issue where the parameters are sent in the req.query instead of req.body when making post requests to the endpoint. While this setup works for GET requests, it poses problems for testing post endpoints.

The apiResolver function only accepts a query parameter and does not provide an option to override the body. How can I effectively test my post endpoints under these circumstances?

Answer №1

To pass the parameters in the request body and introduce a parameter for controlling that functionality, I successfully overrode it by following this method:

import { IncomingMessage, ServerResponse, createServer } from 'http';

import { NextApiHandler, NextApiRequest, NextApiResponse } from 'next';
import { __ApiPreviewProps, apiResolver } from 'next/dist/next-server/server/api-utils';
import request from 'supertest';

export default (
  handler: NextApiHandler,
  query: Record<string, unknown> | undefined,
  isPost: boolean,
): request.SuperTest<request.Test> =>
  request(
    createServer(async (req: IncomingMessage, res: ServerResponse) => {
      return apiResolver(
        req,
        res,
        isPost ? null : query,
        async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
          if (isPost) {
            req.body = query;
          }
          handler(req, res);
        },
        {} as __ApiPreviewProps,
        false,
      );
    }),
  );


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

The <a> tag does not lead to a different webpage and cannot be clicked on

I have developed a web component that includes a method to generate a copyright string: '<p>Copyright © 2020 John Doe<a href="https://www.example.com">. Terms of Use</a></p>' After creating the string, I conver ...

Is there a way to instruct Alexa/Jovo to incorporate just one render document in its response?

Within my project, there are multiple outputs, but I am specifically focused on an output that presents 2 directives: an APL and an APLA render document. My component is set up to handle this in the following way: @Handle({ global: true, prioritiz ...

Using styled-components to enhance an existing component by adding a new prop for customization of styles

I am currently using styled-components to customize the styling of an existing component, specifically ToggleButton from material ui. However, I want my new component to include an additional property (hasMargin) that will control the style: import {Toggle ...

Use contextual type when determining the return type of a function, rather than relying solely on

When using Typescript 2.2.2 (with the strictNullChecks option set to true), I encountered an unexpected behavior. Is this a bug or intentional? interface Fn { (value: any): number; } var example1: Fn = function(value) { if (value === -1) { ...

The issue encountered is a TypeError stating that it is unable to retrieve properties of an undefined value, specifically in relation to the 'imageUrl

When I include the following line of HTML code: <td> <img align="center" [src]="productByBarCode.imageUrl" /> </td> An error is thrown by the console: ERROR TypeError: Cannot read properties of undefined (reading &a ...

Obscuring CSS class names for NextJS 14 using Instagram-inspired styling and SWC technology

It's interesting to see how Instagram Direct utilizes Tailwind CSS for their class names, but they have somehow obfuscated it to make it non-readable and prevent content crawling bots. I've searched for solutions online, but it seems like not man ...

Tips for successfully sending an interface to a generic function

Is there a way to pass an interface as a type to a generic function? I anticipate that the generic function will be expanded in the future. Perhaps the current code is not suitable for my problem? This piece of code is being duplicated across multiple fil ...

NextJs not processing Bootstrap form submissions

I’m struggling to figure out why my form isn’t submitting when I click the submit button. The backend seems fine because Postman successfully sends the information to the database. However, nothing happens when I try to submit the form. My tech stack ...

The error message "React/display-name error: Component definition does not include a display name

When trying to upload my project to Vercel NextJS, I encountered an error stating that the display name 'react' is missing. After researching online, it seems this error occurs when a function is not exported correctly. Can anyone help me with th ...

Running an ESNext file from the terminal: A step-by-step guide

Recently, I delved into the world of TypeScript and developed an SDK. Here's a snippet from my .tsconfig file that outlines some of the settings: { "compilerOptions": { "moduleResolution": "node", "experimentalDecorators": true, "module ...

Customizing Material UI Select for background and focus colors

I am looking to customize the appearance of the select component by changing the background color to "grey", as well as adjusting the label and border colors from blue to a different color when clicking on the select box. Can anyone assist me with this? B ...

Issues persist with the majority of tests in Jest 24.1 and Babel 7.3.3

After struggling with this issue for days, I've decided to seek help from the experts at StackOverflow. Your assistance would be greatly appreciated :) Here is the error that's causing trouble => Identifier 'global' has already been ...

TypeError thrown by Basic TypeScript Class

I'm encountering an issue where TypeScript is throwing a TypeError when trying to use the class Literal from file Classes.tsx in file App.tsx, even though they are in the same file. Strangely, everything works fine on typescriptlang.org/play. // Class ...

Having difficulty initializing a constant object in TypeScript

Encountering an error while attempting to compile my code using Angular 7.2.0 and TypeScript version 3.2.2: Error TS1005: ',' expected.**… The issue seems to be arising from the line where I am trying to define a const object. addAppareil( ...

Encountering an error with loading in Angular may require a suitable loader

I am currently working on integrating an AWS QuickSight dashboard into an Angular application. For implementation in Angular, I am referring to the following URL: https://github.com/awslabs/amazon-quicksight-embedding-sdk Could someone provide me with sa ...

Processing Data with JavaScript

I am new to working with JavaScript, coming from the Python world. I need some assistance. Currently, I am retrieving data from the back end that has the following structure: { "Airports": { "BCN": { "Arrivals": [ ...

What is the best way to use lodash to group objects that contain nested objects?

Currently utilizing Typescript in conjunction with Lodash! Upon retrieving data from the database, here is the resulting output: [ { "unitPrice": 0.01, "code": "92365524", "description": "Broto gr ...

Angular: Enable function to await Observable completion before returning result

I require assistance with the user function below: getUser(uuid: string): Observable<WowUserDataModel> { let user: WowUserDataModel = { login: null, userUuid: uuid, firstName: null, lastName: null, displayName: nul ...

Issue with Angular2: The [routerLinkActive] directive does not update when using _router.navigate

My app includes several routerLinks that I have styled using [routerLinkActive]="['active']". Everything works perfectly when I click on one of the routerLinks to navigate. However, when I try to navigate using: this._router.navigate( [ thisUrl ...

Issue with Next.js 14 favicon.ico not displaying on Chrome browser

When I tried to replace the favicon.ico, Chrome was unable to display it. It appears to be a bug related to using app router. /-app /-favicon.ico I noticed that many others have encountered this issue as well, but I found a solution: 1. Rename favic ...