Next.js Discord

Discord Forum

Testing API Route Handlers with Jest

Unanswered
Alligator mississippiensis posted this in #help-forum
Open in Discord
Alligator mississippiensisOP
I currently have a route handler that makes a POST request to an existing API. I've defined it like so:
export async function POST(req: NextRequest) {
  // destrucure req for data
  try {
    const response = await fetch("/api/something");

    if (response.status !== 200) {
      return NextResponse.json({
        status: response.status,
        error: response.statusText,
      });
    }

    return NextResponse.json({ status: 'success' });
  } catch (err) {
    return new Response(null, { status: 500 });
  }
}


The functionality of this router handler works perfectly fine and is doing what it's intended to do. However, I can't for the life of me unit test this. I've read so many articles online and haven't come across a conclusive solution to this problem I'm facing. What I've done so far is:

/**
 * @jest-environment-node
 */

import 'isomorphic-fetch';

import { NextRequest, NextResponse } from 'next/server';
import { createMocks, RequestMethod } from 'node-mocks-http';

import { mockResponse } from './mocks';
import { POST } from './route';
import * as apiModule from './route';

describe('/api/something', () => {
  function mockRequestResponse(method: RequestMethod) {
    const { req, res }: { req: NextRequest; res: NextResponse } =
      createMocks({
        method,
        headers: { 'content-type': 'application/json' },
      });
    return { req, res };
  }

  it('should return a successful response', async () => {
    const { req, res } = mockRequestResponse('POST');

    const response = await POST(req);

    expect(response.status).toBe(200);
  });
});

some imports are unused from previous attempts to get this working

No matter what I do, response.status is always 500. I've tried mocking and creating a spy for fetch with the global.fetch = jest.fn(...) but that didn't help. I'm truly stumped and don't really know how to proceed. Any help is appreciated!

1 Reply

Scale parasitoid
@Alligator mississippiensis Did you find any solution for this?