eugef / node-mocks-http

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

Typescript: Type 'string' is not assignable to type 'Body | undefined' #233

Closed Shestac92 closed 6 months ago

Shestac92 commented 3 years ago

I found that Body interface supports only [key: string]: any;. But in many projects, the body may include stringified JSON, like this:

const { req, res } = createMocks({
      method: 'POST',
      body: JSON.stringify({ config: 'some config' }),
    });

Because of that, the eslint throws the error below:

error

Probably, we can add a type like export type BodyString = string; and apply it to the RequestOptions interface like this:

    export interface RequestOptions {
        method?: RequestMethod;
        url?: string;
        originalUrl?: string;
        baseUrl?: string;
        path?: string;
        params?: Params;
        session?: Session;
        cookies?: Cookies;
        signedCookies?: Cookies;
        headers?: Headers;
        body?: Body | BodyString;         // or BodyString
        query?: Query;
        files?: Files;

        // Support custom properties appended on Request objects.
        [key: string]: any;
    }

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!

github-actions[bot] commented 3 years ago

Stale issue message

dbrosio3 commented 2 years ago

This is happening to me as well

julianferres commented 1 year ago

Any updates/workarounds for this?

Stalex89 commented 9 months ago

@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
}
eugef commented 9 months ago

@julianferres @dbrosio3 please try the latest release v1.14.0 it has fixes specifically to improve testing in Next.js with TS

Stalex89 commented 9 months ago

@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");
  });
});
eugef commented 9 months ago

Hi @mhaligowski, can you please check the comment above. How difficult would it be to add support for NextRequest and NextResponse types?

Meags27 commented 9 months ago

@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);
        },
      });
Stalex89 commented 9 months ago

@Meags27 this workaround worked for me as well, thank you!

mhaligowski commented 9 months ago

Hi @mhaligowski, can you please check the comment above. How difficult would it be to add support for NextRequest and NextResponse 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.

mhaligowski commented 9 months ago

@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.

github-actions[bot] commented 7 months ago

Stale issue message