Closed Shestac92 closed 6 months ago
Stale issue message
This is happening to me as well
Any updates/workarounds for this?
@julianferres @dbrosio3 If you still have this issue, here is a post with a small workaround:
https://www.reddit.com/r/nextjs/comments/16z4l49/how_the_hell_do_i_test_nextjs_app_router_api/ https://gist.github.com/william-murphy/01c6e597fc0df7f27df7c020635fdfac
In short just add the typecheck for request to the API route handler as follows:
export async function POST(req: NextRequest) {
const body = req instanceof EventEmitter ? req.body : await req.json();
...rest of the code
}
@julianferres @dbrosio3 please try the latest release v1.14.0 it has fixes specifically to improve testing in Next.js with TS
@eugef could you please check how it works with app router (Next.js v.13+) ?
I see it only accepts types of NextApiRequest and NextApiResponse which are the part of pages router. It does not accept NextRequest and NextResponse types from app router.
Reference to api types: Pages router: https://nextjs.org/docs/pages/building-your-application/routing/api-routes#adding-typescript-types App router: https://nextjs.org/docs/app/building-your-application/routing/route-handlers
I still have the following error while trying to run the test with mocking the API route:
req.json is not a function
TypeError: req.json is not a function
Api route example:
//app/api/example/route.ts
export async function POST(req: NextRequest) {
const body = await req.json();
...rest of the code...
return NextResponse.json({ ...body }, { status: 200 });
Test file:
/**
* @jest-environment node
*/
import {
createMocks,
MockRequest,
RequestOptions,
ResponseOptions,
} from "node-mocks-http";
import { POST as exampleRouteHandler } from "@/app/api/example/route";
import { NextRequest, NextResponse } from "next/server";
describe("API: /api/example", () => {
function mockRequestResponse(
reqOptions?: RequestOptions,
resOptions?: ResponseOptions,
) {
const { req, res }: { req: NextRequest; res: NextResponse } =
createMocks(reqOptions, resOptions);
return { req, res };
}
it("should return a successful response from API", async () => {
const payload = {
name: "John doe",
email: "john.doe@example.com",
};
const { req, res } = mockRequestResponse({
method: "POST",
body: payload,
headers: {
"Content-Type": "application/json",
},
});
await signupRouteHandler(req);
const responseJson = await res.json();
expect(responseJson.statusCode).toBe(200);
expect(responseJson._headers).toEqual({
"content-type": "application/json",
});
expect(responseJson.statusMessage).toEqual("OK");
});
});
Hi @mhaligowski, can you please check the comment above.
How difficult would it be to add support for NextRequest
and NextResponse
types?
@eugef could you please check how it works with app router (Next.js v.13+) ?
I see it only accepts types of NextApiRequest and NextApiResponse which are the part of pages router. It does not accept NextRequest and NextResponse types from app router.
Reference to api types: Pages router: https://nextjs.org/docs/pages/building-your-application/routing/api-routes#adding-typescript-types App router: https://nextjs.org/docs/app/building-your-application/routing/route-handlers
I still have the following error while trying to run the test with mocking the API route:
req.json is not a function TypeError: req.json is not a function
Api route example:
//app/api/example/route.ts export async function POST(req: NextRequest) { const body = await req.json(); ...rest of the code... return NextResponse.json({ ...body }, { status: 200 });
Test file:
/** * @jest-environment node */ import { createMocks, MockRequest, RequestOptions, ResponseOptions, } from "node-mocks-http"; import { POST as exampleRouteHandler } from "@/app/api/example/route"; import { NextRequest, NextResponse } from "next/server"; describe("API: /api/example", () => { function mockRequestResponse( reqOptions?: RequestOptions, resOptions?: ResponseOptions, ) { const { req, res }: { req: NextRequest; res: NextResponse } = createMocks(reqOptions, resOptions); return { req, res }; } it("should return a successful response from API", async () => { const payload = { name: "John doe", email: "john.doe@example.com", }; const { req, res } = mockRequestResponse({ method: "POST", body: payload, headers: { "Content-Type": "application/json", }, }); await signupRouteHandler(req); const responseJson = await res.json(); expect(responseJson.statusCode).toBe(200); expect(responseJson._headers).toEqual({ "content-type": "application/json", }); expect(responseJson.statusMessage).toEqual("OK"); }); });
I ended up fixing the .json issue by mocking that
const { req } = createMocks({
method: "POST",
url: "/api/account/email",
body: mockRequestData,
json: () => {
return Promise.resolve(mockRequestData);
},
});
@Meags27 this workaround worked for me as well, thank you!
Hi @mhaligowski, can you please check the comment above. How difficult would it be to add support for
NextRequest
andNextResponse
types?
Sorry it took me a little longer to reply!
I don't think adding the support will be difficult at all. The potential problem I see is that the App Router classes (NextRequest
and NextResponse
) actually extend Fetch API requests and responses, for some reason, which IIUC are actually the client requests and responses, not the server.
I guess we could try adding | Request
to the type definition, let me try this over the weekend.
@Stalex89 if possible, would you be able to test out #291 ?
NextJS made a little weird decision (IMHO) to utilize Web API's object as base classes. IIUC those generally represent HTTP requests from the client, compared to Express or IncomingMessage, which represent server-side objects.
I don't think it messes node-mocks-https
though, some things might be a little trickier to mock, but should behave the same nonetheless.
Stale issue message
I found that
Body
interface supports only[key: string]: any;
. But in many projects, the body may include stringified JSON, like this:Because of that, the
eslint
throws the error below:Probably, we can add a type like
export type BodyString = string;
and apply it to theRequestOptions
interface like this:It will solve the issue for eslint users. Probably there is a more elegant solution but the idea remains the same. Also, any workarounds are welcome!