Next.js Discord

Discord Forum

createMocks and NextRequest

Answered
Kokoni posted this in #help-forum
Open in Discord
Avatar
KokoniOP
Hey y'all! I want to do some unit testing.

In the below example, you will see that I am trying to import the actual route and call the function which is what I think should be the right path. Only problem is that createMocks does not create a NextRequest, but a normal Request. How should I go about making a NextRequest?

Here is what I have so far...

import "@testing-library/jest-dom";
import { createMocks } from "node-mocks-http";

describe("/api/user", () => {
  test("Gets the user based on bearer token", async () => {
    const { req, res } = createMocks({
      method: "GET",
      headers: {
        Authorization: "Bearer token",
      },
    });

    // error on `req`
    const response = await (
      await import("@/app/api/user/route")
    ).GET(req, {
      searchParams: {
        // omitted
      },
    });

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

3 Replies

Avatar
KokoniOP
Hi I figured this out I want to share my answer
Give me a sec and I will share
Answer