Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
Shestac92 opened this issue Feb 24, 2021 · 12 comments · Fixed by #291
Closed

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

Shestac92 opened this issue Feb 24, 2021 · 12 comments · Fixed by #291

Comments

@Shestac92
Copy link

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
Copy link

Stale issue message

@dbrosio3
Copy link

dbrosio3 commented Jul 1, 2022

This is happening to me as well

@julianferres
Copy link

Any updates/workarounds for this?

@Stalex89
Copy link

@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
Copy link
Owner

eugef commented Dec 12, 2023

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

@Stalex89
Copy link

Stalex89 commented Dec 12, 2023

@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: "[email protected]",
    };
    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 eugef reopened this Dec 29, 2023
@eugef
Copy link
Owner

eugef commented Dec 29, 2023

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

@Meags27
Copy link

Meags27 commented Jan 1, 2024

@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: "[email protected]",
    };
    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
Copy link

Stalex89 commented Jan 3, 2024

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

@mhaligowski
Copy link
Contributor

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
Copy link
Contributor

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

Copy link

github-actions bot commented Mar 8, 2024

Stale issue message

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

7 participants