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?