node-mocks-http icon indicating copy to clipboard operation
node-mocks-http copied to clipboard

Not compatible with the Next.js "app" router

Open scottned opened this issue 1 year ago • 3 comments

It seems that this package is not compatible with Next's newer "app" router. The older "page" router works fine because its NextApiRequest extends IncomingMessage as your package requires. However, the "app" router's NextRequest does not -- it extends the standard Request interface of the fetch API.

Is this a known issue? Am I missing something obvious? It took awhile today to sort all this out. If it's correct, it would be helpful to others to have a note on the README.md.

By the way, I think you have a typo in your README.md that refers to http.IncomingRequest, but it should say http.IncomingMessage

scottned avatar Feb 20 '24 20:02 scottned

I'm not sure what we're getting out of mocking the request since we're just passing it into the handler anyways. Might as well just create the request object. This worked for me (just creating the NextRequest object, not mocking anything)

import { POST } from '@/src/app/api/feedback/route';
import { NextRequest } from 'next/server';

describe('SubmitFeedback', () => {
  it('should create a feedback entry', async () => {
    const body : {} = {
      feedback: 'Love your site!'
    }

    const headers = {
      'Content-Type': 'application/json',
      'accept-language': 'en-US'
    }

    const params: RequestInit = {
      headers: headers,
      method: "POST",
      body: JSON.stringify(body)
    }

    const req = new NextRequest('http://doesntmatter', params);

    const response = await POST(req);

    expect(response).toBeDefined();
  });
});

DaneSharafinski avatar Mar 03 '24 16:03 DaneSharafinski

I tried to circunvent this problem as @DaneSharafinski said, but i have a problems when uploading binary files, because the NextRequest constructor automatically tries to parse the body to uint8Array, also tried with the usual request constructor but to no avail. I also tried manually testing the binary upload outside jest with postman, and works fine maybe its a next14 thing?

Centorios avatar May 10 '24 21:05 Centorios

Stale issue message

github-actions[bot] avatar Jul 10 '24 01:07 github-actions[bot]

Stale issue message

github-actions[bot] avatar Sep 28 '24 01:09 github-actions[bot]