Next.js Discord

Discord Forum

how do you test api in nextJS?

Unanswered
Pacific sand lance posted this in #help-forum
Open in Discord
Avatar
Pacific sand lanceOP
I want to use the supertest library, I've used it with vanilla react. but it requires express, but nextjs doesnt have expres right? is it right to try to use supertest, is there something else that people use today?

5 Replies

Avatar
Pacific sand lanceOP
https://github.com/mtbrault/nextjs-http-supertest i found this but it doesnt seem to be that popular
Avatar
Marchy
You should be able to use something like node-mocks-http and do standard unit testing with jest
Avatar
Pacific sand lanceOP
node-mocks-http doesnt seem to understand NextResponse
Avatar
Pacific sand lanceOP
ok, it works but i had to change
export async function GET(req: NextApiRequest, res: NextApiResponse) {
  return NextResponse.json({ message: "Sup" });
}
to
export async function GET(req: NextApiRequest, res: NextApiResponse) {
  return res.status(200).json({ message: "Sup" });
}
If i put next response in it, then it doesnt work. here is my test
// Import the route file and the library
import { createMocks } from "node-mocks-http";
import { GET } from "@/app/api/route";
// Write a test using Jest
test("should return a greeting message", async () => {
  // Create mock request and response objects
  const { req, res } = createMocks({
    method: "GET",
  });

  // Call the route function with the mock objects
  await GET(req, res);

  // Assert the expected behavior
  expect(res._getStatusCode()).toBe(200);
  expect(res._getJSONData().message).toBe("Sup");
});