how do you test api in nextJS?
Unanswered
Pacific sand lance posted this in #help-forum
![Avatar](https://cdn.discordapp.com/embed/avatars/1.png)
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](https://cdn.discordapp.com/embed/avatars/1.png)
Pacific sand lanceOP
https://github.com/mtbrault/nextjs-http-supertest i found this but it doesnt seem to be that popular
![Avatar](https://cdn.discordapp.com/avatars/203709756689350656/75cbd80082a0a625e3a5f4ef3d8ae2ae.webp?size=256)
Marchy
You should be able to use something like
node-mocks-http
and do standard unit testing with jest![Avatar](https://cdn.discordapp.com/embed/avatars/1.png)
Pacific sand lanceOP
node-mocks-http doesnt seem to understand NextResponse
![Avatar](https://cdn.discordapp.com/avatars/203709756689350656/75cbd80082a0a625e3a5f4ef3d8ae2ae.webp?size=256)
Marchy
There's a guide here
https://medium.com/@zachshallbetter/testing-routes-in-next-js-13-c09b3eb795c2
https://medium.com/@zachshallbetter/testing-routes-in-next-js-13-c09b3eb795c2
![Avatar](https://cdn.discordapp.com/embed/avatars/1.png)
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");
});