eugef / node-mocks-http

Mock 'http' objects for testing Express,js, Next.js and Koa routing functions
Other
755 stars 134 forks source link

Not compatible with the Next.js "app" router #295

Open scottned opened 7 months ago

scottned commented 7 months ago

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

DaneSharafinski commented 7 months ago

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();
  });
});
Centorios commented 4 months ago

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?

github-actions[bot] commented 2 months ago

Stale issue message

github-actions[bot] commented 6 days ago

Stale issue message