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

Converting Epoch time to date in NextJS

In my NextJS app, I have a date displayed in a div. <div>{post.createdat}</div> The date is shown in epoch time (1609553315666), indicating the number of seconds that have elapsed since 1970. I'm wondering if there's a way to conver ...

Error message displaying 'class-transformer returning undefined'

I'm new to working with the class-transformer library. I have a simple Product class and JSON string set up to load a Product object. However, I'm encountering an issue where even though I can see the output indicating that the transformation was ...

Exceed the capacity of a React component

Imagine having a React component that can render either a <button>, an <a>, or a React Router <Link> based on different props passed to it. Is it possible to overload this component in order to accept the correct props for each scenario? ...

Retrieve data dynamically when requested with GetServerSideProps

Utilizing the getServerSideProps method to dynamically fetch data at request time. Initially, my application retrieves data from pageNumber = 1. export default function Index({ cmsData }: IndexProps) { return ( // some code <button> Button ...

Understanding TypeScript typing when passing arguments to the Object.defineProperty function

After reviewing all the suggested answers, including: in Typescript, can Object.prototype function return Sub type instance? I still couldn't find a solution, so I'm reaching out with a new question. My goal is to replicate Infix notation in J ...

Encountered an issue while attempting to authenticate CMS signature using pkijs

I am attempting to validate a CMS signature generated with open ssl using the following command: $ openssl cms -sign -signer domain.pem -inkey domain.key -binary -in README.md -outform der -out signature Below is my code utilizing pkijs: import * as pkij ...

The string returned from the Controller is not recognized as a valid JSON object

When attempting to retrieve a string from a JSON response, I encounter an error: SyntaxError: Unexpected token c in JSON at position In the controller, a GUID is returned as a string from the database: [HttpPost("TransactionOrderId/{id}")] public asyn ...

Retrieving the return type of generic functions stored in a map

In this unique scenario, I have a dictionary with polymorphic functions that accept the same argument but return different results: const dict = { one: { foo<A>(a: A) { return [a] as const } }, two: { foo<A>(a: A) { ...

Why is NestJs having trouble resolving dependencies?

Recently delving into NestJs, I followed the configuration instructions outlined in https://docs.nestjs.com/techniques/database, but I am struggling to identify the issue within my code. Error: Nest cannot resolve dependencies of the AdminRepository ...

Next.js: How to retrieve route parameter within getServerSideProps

I need to retrieve data from my Supabase table using the ID provided in the URL slug, for example localhost:3000/book/1, and then display information about that specific book on a page built with Next.js. Table https://i.stack.imgur.com/t5z7d.png book/[ ...

What is the process to subscribe and obtain data from a server-to-user channel using pusher-js?

I am currently hosting my application using next.js on Vercel. I want to integrate Pusher to provide real-time messages to users in a private and secure manner. Despite successful log entries, I am facing challenges in subscribing to the channel and retrie ...

What is the method for retrieving the locale value from the configuration in Next.js?

How can I retrieve the i18n.defaultLocale value from my Next.js app configuration? I thought it would be simple, but I'm struggling to find a clear solution for accessing the config settings in Next.js. Is there a specific built-in method for this, or ...

Accessing nested objects within an array using lodash in typescript

After analyzing the structure of my data, I found it to be in this format: {property: ["a","b"], value : "somevalue" , comparison : "somecomparison"} I am looking for a way to transform it into a nested object like so: { "properties": { "a": { ...

Using typescript for Gnome shell extension development. Guidelines on importing .ts files

I'm currently working on a gnome shell extension using typescript, but I've encountered issues when trying to import .ts files. The Gnome shell documentation suggests configuring the tsconfig file as outlined in this Gnome typescript docs: { &q ...

Error message 'Module not found' occurring while utilizing dynamic import

After removing CRA and setting up webpack/babel manually, I've encountered issues with dynamic imports. The following code snippet works: import("./" + "CloudIcon" + ".svg") .then(file => { console.log(file); }) However, this snip ...

Perplexed by the persistent failure of this Jasmine test accompanied by a vexing "timer in queue" error

I'm attempting to test a function that uses RxJS to broadcast long press events to subscribers. Below is the implementation of the function: export function watchForLongPress(target: HTMLElement) { let timer: number; const notifier = new Subject& ...

Angular 5 ngx-modialog issue TS2307: Module 'ngx-modialog/plugins/vex' not located

After installing module ngx-modialog using the Angular 5 CLI like this: npm install --save ngx-modialog I then added it to my app.module.ts: import { VexModalModule } from "ngx-modialog/plugins/vex"; import { ModalModule } from "ngx-modialog"; @NgModul ...

The 'required' validator in Mongoose seems to be malfunctioning

I've been attempting to validate the request body against a Mongoose model that has 'required' validators, but I haven't been successful in achieving the desired outcome so far. My setup involves using Next.js API routes connected to Mo ...

Implementing OTP input using Material UI textfield

Is it possible to create an OTP input using the textfield component of material UI in a React TypeScript project? I've seen examples where people have implemented this with regular input fields, but I'm specifically interested in utilizing the te ...

Mastering Jest unit testing for Node.js Socket functionality

I am currently working on writing unit tests for a socket using JEST. Although the test cases are passing, the code is not being covered in the code coverage report. I am unsure of where I may have made a mistake, especially since I am still in the learnin ...