Giter Club home page Giter Club logo

next-test-api-route-handler's Introduction

Confidently test your Next.js API routes in an isolated Next-like environment


Black Lives Matter! Last commit timestamp Codecov Source license Uses Semantic Release!

NPM version Monthly Downloads


next-test-api-route-handler

Trying to unit test your Next.js API routes? Tired of hacking something together with express or node-mocks-http or writing a bunch of boring dummy infra just to get some passing tests? And what does a "passing test" mean anyway when your handlers aren't receiving actual NextRequest objects and aren't being run by Next.js itself?

Next.js patches the global fetch function, for instance. If your tests aren't doing the same, you're making space for bugs!

Is it vexing that everything explodes when your App Router handlers call headers() or cookies() or any of the other route-specific helper functions? Or maybe you want your Pages Router handlers to receive actual NextApiRequest and NextApiResponse objects?

Sound interesting? Then want no longer! 🤩

next-test-api-route-handler (NTARH) uses Next.js's internal resolvers to precisely emulate route handling. To guarantee stability, this package is automatically tested against each release of Next.js and Node.js. Go forth and test confidently!


Note that App Router support begins with [email protected] (why?)



Install

npm install --save-dev next-test-api-route-handler

See the appendix for legacy Next.js support options.

Also see the appendix if you're using jest and jest-environment-jsdom.

Usage

Important

NTARH must always be the first import in your test file. This is due to the way Next.js is written and distributed. See the appendix for technical details.

// ESM
import { testApiHandler } from 'next-test-api-route-handler'; // ◄ Must be first

... all other imports ...
// CJS
const { testApiHandler } = require('next-test-api-route-handler'); // ◄ Must be first

... all other imports ...

Quick Start: App Router

/* File: test/unit.test.ts */

import { testApiHandler } from 'next-test-api-route-handler'; // ◄ Must be first import
// Import the handler under test from the app directory
import * as appHandler from '../app/your-endpoint/route';

it('does what I want', async () => {
  await testApiHandler({
    appHandler,
    // requestPatcher is optional
    requestPatcher(request) {
      request.headers.set('key', process.env.SPECIAL_TOKEN);
    },
    // responsePatcher is optional
    async responsePatcher(response) {
      const json = await response.json();
      return Response.json(
        json.apiSuccess ? { hello: 'world!' } : { goodbye: 'cruel world' }
      );
    },
    async test({ fetch }) {
      const res = await fetch({ method: 'POST', body: 'dummy-data' });
      await expect(res.json()).resolves.toStrictEqual({ hello: 'world!' }); // ◄ Passes!
    }
  });
});

Quick Start: Edge Runtime

/* File: test/unit.test.ts */

import { testApiHandler } from 'next-test-api-route-handler'; // ◄ Must be first import
// Import the handler under test from the app directory
import * as edgeHandler from '../app/your-edge-endpoint/route';

it('does what I want', async function () {
  // NTARH supports optionally typed response data via TypeScript generics:
  await testApiHandler<{ success: boolean }>({
    // Only appHandler supports edge functions. The pagesHandler prop does not!
    appHandler: edgeHandler,
    // requestPatcher is optional
    requestPatcher(request) {
      return new Request(request, {
        body: dummyReadableStream,
        duplex: 'half'
      });
    },
    async test({ fetch }) {
      // The next line would cause TypeScript to complain:
      // const { luck: success } = await (await fetch()).json();
      await expect((await fetch()).json()).resolves.toStrictEqual({
        success: true // ◄ Passes!
      });
    }
  });
});

Quick Start: Pages Router

/* File: test/unit.test.ts */

import { testApiHandler } from 'next-test-api-route-handler'; // ◄ Must be first import
// Import the handler under test and its config from the pages/api directory
import * as pagesHandler from '../pages/api/your-endpoint';

it('does what I want', async () => {
  // NTARH supports optionally typed response data via TypeScript generics:
  await testApiHandler<{ hello: string }>({
    pagesHandler,
    requestPatcher: (req) => {
      req.headers = { key: process.env.SPECIAL_TOKEN };
    },
    test: async ({ fetch }) => {
      const res = await fetch({ method: 'POST', body: 'data' });
      // The next line would cause TypeScript to complain:
      // const { goodbye: hello } = await res.json();
      const { hello } = await res.json();
      expect(hello).toBe('world'); // ◄ Passes!
    }
  });
});

API

NTARH exports a single function, testApiHandler(options), that accepts an options object as its only parameter.

At minimum, options must contain the following properties:

  • At least one of the appHandler or pagesHandler options, but not both.
  • The test option.

For example:

Caution

Ensuring testApiHandler is imported before any Next.js package (like 'next/headers' below) is crucial to the proper function of NTARH. Doing otherwise will result in undefined behavior.

import { testApiHandler } from 'next-test-api-route-handler';
import { headers } from 'next/headers';

await testApiHandler({
  appHandler: {
    dynamic: 'force-dynamic',
    GET(_request) {
      return Response.json(
        {
          // Yep, those fancy helper functions work too!
          hello: headers().get('x-hello')
        },
        { status: 200 }
      );
    }
  },
  async test({ fetch }) {
    await expect(
      (await fetch({ headers: { 'x-hello': 'world' } })).json()
    ).resolves.toStrictEqual({
      hello: 'world'
    });
  }
});

appHandler

⪢ API reference: appHandler

The actual route handler under test (usually imported from app/*). It should be an object and/or exported module containing one or more valid uppercase HTTP method names as keys, each with an async handling function that accepts a NextRequest and a context (i.e. { params }) as its two parameters. The object or module can also export other configuration settings recognized by Next.js.

await testApiHandler({
  params: { id: 5 },
  appHandler: {
    async POST(request, { params: { id } }) {
      return Response.json(
        { special: request.headers.get('x-special-header'), id },
        { status: 200 }
      );
    }
  },
  async test({ fetch }) {
    expect((await fetch({ method: 'POST' })).status).toBe(200);

    const result2 = await fetch({
      method: 'POST',
      headers: { 'x-special-header': 'x' }
    });

    expect(result2.json()).toStrictEqual({ special: 'x', id: 5 });
  }
});

See also: rejectOnHandlerError and the section Working Around Next.js fetch Patching.

pagesHandler

⪢ API reference: pagesHandler

The actual route handler under test (usually imported from pages/api/*). It should be an async function that accepts NextApiRequest and NextApiResponse objects as its two parameters.

await testApiHandler({
  params: { id: 5 },
  pagesHandler: (req, res) => res.status(200).send({ id: req.query.id }),
  test: async ({ fetch }) =>
    expect((await fetch({ method: 'POST' })).json()).resolves.toStrictEqual({
      id: 5
    })
});

See also: rejectOnHandlerError.

test

⪢ API reference: test

An async or promise-returning function wherein test assertions can be run. This function receives one destructured parameter: fetch, which is a wrapper around Node's global fetch function. Use this to send HTTP requests to the handler under test.

Caution

Note that fetch's resource parameter, i.e. the first parameter in fetch(...), is omitted.

⚙ Handling Redirections

Starting with version 4.0.4, NTARH sets the fetch(...) options parameter's redirect property to 'manual' by default. This prevents the WHATWG/undici fetch function from throwing a fetch failed/redirect count exceeded error.

If you want to change this value, call fetch with your own custom options parameter, e.g. fetch({ redirect: 'error' }).

⚙ Compatibility with Mock Service Worker

Starting with version 4.0.0, NTARH ships with Mock Service Worker (msw) support by adding the x-msw-intention: "bypass" and x-msw-bypass: "true" headers to all requests.

If necessary, you can override this behavior by setting the appropriate headers to some other value (e.g. "none") via fetch's customInit parameter (not requestPatcher). This comes in handy when testing functionality like arbitrary response redirection (or via the Pages Router).

For example:

import { testApiHandler } from 'next-test-api-route-handler';
import { http, passthrough, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';

const server = setupServer(/* ... */);

beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));

afterEach(() => {
  server.resetHandlers();
});

afterAll(() => server.close());

it('redirects a shortened URL to the real URL', async () => {
  expect.hasAssertions();

  // e.g. https://xunn.at/gg => https://www.google.com/search?q=next-test-api-route-handler
  // shortId would be "gg"
  // realLink would be https://www.google.com/search?q=next-test-api-route-handler

  const { shortId, realLink } = getUriEntry();
  const realUrl = new URL(realLink);

  await testApiHandler({
    appHandler,
    params: { shortId },
    test: async ({ fetch }) => {
      server.use(
        http.get('*', async ({ request }) => {
          return request.url === realUrl.href
            ? HttpResponse.json({ it: 'worked' }, { status: 200 })
            : passthrough();
        })
      );

      const res = await fetch({
        headers: { 'x-msw-intention': 'none' } // <==
      });

      await expect(res.json()).resolves.toMatchObject({ it: 'worked' });
      expect(res.status).toBe(200);
    }
  });
});

response.cookies

As of version 2.3.0, the response object returned by fetch() includes a non-standard cookies field containing an array of objects representing set-cookie response header(s) parsed by the cookie package. Use the cookies field to easily access a response's cookie data in your tests.

Here's an example taken straight from the unit tests:

import { testApiHandler } from 'next-test-api-route-handler';

it('handles multiple set-cookie headers', async () => {
  expect.hasAssertions();

  await testApiHandler({
    pagesHandler: (_, res) => {
      // Multiple calls to setHeader('Set-Cookie', ...) overwrite previous, so
      // we have to set the Set-Cookie header properly
      res
        .setHeader('Set-Cookie', [
          serializeCookieHeader('access_token', '1234', {
            expires: new Date()
          }),
          serializeCookieHeader('REFRESH_TOKEN', '5678')
        ])
        .status(200)
        .send({});
    },
    test: async ({ fetch }) => {
      expect((await fetch()).status).toBe(200);
      await expect((await fetch()).json()).resolves.toStrictEqual({});
      expect((await fetch()).cookies).toStrictEqual([
        {
          access_token: '1234',
          // Lowercased cookie property keys are available
          expires: expect.any(String),
          // Raw cookie property keys are also available
          Expires: expect.any(String)
        },
        { refresh_token: '5678', REFRESH_TOKEN: '5678' }
      ]);
    }
  });
});

rejectOnHandlerError

⪢ API reference: rejectOnHandlerError

As of version 2.3.0, unhandled errors in the pagesHandler/appHandler function are kicked up to Next.js to handle.

Important

This means testApiHandler will NOT reject or throw if an unhandled error occurs in pagesHandler/appHandler, which typically includes failing expect() assertions.

Instead, the response returned by fetch() in your test function will have a HTTP 500 status thanks to how Next.js deals with unhandled errors in production. Prior to 2.3.0, NTARH's behavior on unhandled errors and elsewhere was inconsistent. Version 3.0.0 further improved error handling, ensuring no errors slip by uncaught.

To guard against false negatives, you can do either of the following:

  1. Make sure the status of the fetch() response is what you're expecting:
const res = await fetch();
...
// For this test, a 403 status is what we wanted
expect(res.status).toBe(403);
...
const res2 = await fetch();
...
// Later, we expect an "unhandled" error
expect(res2.status).toBe(500);
  1. If you're using version >=3.0.0, you can use rejectOnHandlerError to tell NTARH to intercept unhandled handler errors and reject the promise returned by testApiHandler instead of relying on Next.js to respond with HTTP 500. This is especially useful if you have expect() assertions inside your handler function:
await expect(
  testApiHandler({
    rejectOnHandlerError: true, // <==
    pagesHandler: (_req, res) => {
      res.status(200);
      throw new Error('bad bad not good');
    },
    test: async ({ fetch }) => {
      const res = await fetch();
      // By default, res.status would be 500...
      //expect(res.status).toBe(500);
    }
  })
  // ...but since we used rejectOnHandlerError, the whole promise rejects
  // instead
).rejects.toThrow('bad not good');

await testApiHandler({
  rejectOnHandlerError: true, // <==
  appHandler: {
    async GET(request) {
      // Suppose this expectation fails
      await expect(backend.getSomeStuff(request)).resolves.toStrictEqual(
        someStuff
      );

      return new Response(null, { status: 200 });
    }
  },
  test: async ({ fetch }) => {
    await fetch();
    // By default, res.status would be 500 due to the failing expect(). If we
    // don't also expect() a non-500 response status here, the failing
    // expectation in the handler will be swallowed and the test will pass
    // (a false negative).
  }
});
// ...but since we used rejectOnHandlerError, the whole promise rejects
// and it is reported that the test failed, which is probably what you wanted.

requestPatcher (url)

Tip

Manually setting the request url is usually unnecessary. Only set the url if your handler expects it or you want to rely on query string parsing instead of params/paramsPatcher.

💎 Using appHandler

⪢ API reference: requestPatcher, url

requestPatcher is a function that receives a NextRequest object and returns a Request instance. Use this function to edit the request before it's injected into the handler.

Caution

Be wary returning a brand new request from requestPatcher (i.e. new NextRequest(newUrl) instead of new NextRequest(newUrl, oldRequest)), especially one that is missing standard headers added by fetch(...). If you're getting strange JSON-related errors or hanging tests, ensure this is not the cause.

The returned Request instance will be wrapped with NextRequest if it is not already an instance of NextRequest, i.e.:

const returnedRequest = (await requestPatcher?.(request)) || request;
const nextRequest = new NextRequest(returnedRequest, { ... });

If you're only setting the request url, use the url shorthand instead:

await testApiHandler({
  // requestPatcher: (request) => new Request('ntarh:///my-url?some=query', request),
  url: '/my-url?some=query'
});

Note

Unlike the Pages Router's NextApiRequest type, the App Router's NextRequest class does not support relative URLs. Therefore, whenever you pass a relative url string via the url shorthand (e.g. { url: '/my-url?some=query' }), NTARH will wrap that url like so: new URL(url, 'ntarh://'). In this case, your requests will have urls like ntarh:///my-url?some=query.

URL Normalization

By default, when initializing the NextRequest object passed to your handler, if a URL with an empty pathname is encountered, NTARH sets said URL's pathname to "/" on your behalf. Additionally, if said URL is missing host and/or protocol, NTARH sets host to "" and protocol to "ntarh:".

If you want your handler to receive the URL string and resulting NextRequest::nextUrl object exactly as you've typed it, use requestPatcher, which is executed after NTARH does URL normalization.

🔷 Using pagesHandler

⪢ API reference: requestPatcher, url

requestPatcher is a function that receives an IncomingMessage. Use this function to modify the request before it's injected into Next.js's resolver.

If you're only setting the request url, use the url shorthand instead:

await testApiHandler({
  // requestPatcher: (req) => { req.url = '/my-url?some=query'; }
  url: '/my-url?some=query'
});

Note that, unlike with the URL class, the url string can be relative.

responsePatcher

💎 Using appHandler

⪢ API reference: responsePatcher

responsePatcher is a function that receives the Response object returned from appHandler and returns a Response instance. Use this function to edit the response after your handler runs but before it's processed by the server.

🔷 Using pagesHandler

⪢ API reference: responsePatcher

responsePatcher is a function that receives a ServerResponse object. Use this function to edit the response before it's injected into the handler.

paramsPatcher (params)

paramsPatcher is a function that receives an object representing "processed" dynamic segments (aka: routes, slugs).

For example, to test a handler normally accessible from /api/user/:id requires passing that handler a value for the "id" dynamic segment:

await testApiHandler({
  paramsPatcher(params) {
    params.id = 'test-id';
  }
});

Or:

await testApiHandler({
  paramsPatcher: (params) => ({ id: 'test-id' })
});

Parameters can also be passed using the params shorthand:

await testApiHandler({
  params: {
    id: 'test-id'
  }
});

Tip

Due to its simplicity, favor the params shorthand over paramsPatcher.

💎 Using appHandler

⪢ API reference: paramsPatcher, params

If both paramsPatcher and the params shorthand are used, paramsPatcher will receive params as its first argument.

Route parameters should not be confused with query string parameters, which are automatically parsed out from the url and made available via the NextRequest argument passed to your handler.

🔷 Using pagesHandler

⪢ API reference: paramsPatcher, params

If both paramsPatcher and the params shorthand are used, paramsPatcher will receive an object like { ...queryStringURLParams, ...params } as its first argument.

Route parameters should not be confused with query string parameters, which are automatically parsed out from the url and added to the params object before paramsPatcher is evaluated.

Examples

What follows are several examples that demonstrate using NTARH with the App Router and the Pages Router.

Check out the tests for even more examples.

Using the App Router

These examples use Next.js's App Router API.

Testing Apollo's Official Next.js Integration @ app/api/graphql

This example is based on the official Apollo Next.js App Router integration. You can run it yourself by copying and pasting the following commands into your terminal.

The following should be run in a nix-like environment. On Windows, that's WSL. Requires curl, node, and git.

mkdir -p /tmp/ntarh-test/test
cd /tmp/ntarh-test
npm install --force next @apollo/server @as-integrations/next graphql-tag next-test-api-route-handler jest babel-jest @babel/core @babel/preset-env
echo 'module.exports={"presets":["next/babel"]};' > babel.config.js
mkdir -p app/api/graphql
curl -o app/api/graphql/route.js https://raw.githubusercontent.com/Xunnamius/next-test-api-route-handler/main/apollo_test_raw_app_route
curl -o test/integration.test.js https://raw.githubusercontent.com/Xunnamius/next-test-api-route-handler/main/apollo_test_raw_app_test
npx jest

This script creates a new temporary directory, installs NTARH and configures dependencies, downloads the app route and jest test files shown below, and runs the test using jest.

The following is our new app route:

/* File: app/api/graphql/route.js */

import { ApolloServer } from '@apollo/server';
import { startServerAndCreateNextHandler } from '@as-integrations/next';
import { gql } from 'graphql-tag';

const resolvers = {
  Query: {
    hello: () => 'world'
  }
};

const typeDefs = gql`
  type Query {
    hello: String
  }
`;

const server = new ApolloServer({
  resolvers,
  typeDefs
});

const handler = startServerAndCreateNextHandler(server);

export { handler as GET, handler as POST };

And with the following jest test, we ensure our route integrates with Apollo correctly:

/* File: tests/integration.test.js */

import { testApiHandler } from 'next-test-api-route-handler';
// Import the handler under test from the app/api directory
import * as appHandler from '../app/api/graphql/route';

describe('my-test (app router)', () => {
  it('does what I want 1', async () => {
    expect.hasAssertions();

    await testApiHandler({
      appHandler,
      test: async ({ fetch }) => {
        const query = `query { hello }`;

        const res = await fetch({
          method: 'POST',
          headers: {
            'content-type': 'application/json' // Must use correct content type
          },
          body: JSON.stringify({ query })
        });

        await expect(res.json()).resolves.toStrictEqual({
          data: { hello: 'world' }
        });
      }
    });
  });

  it('does what I want 2', async () => {
    // Exactly the same as the above...
  });

  it('does what I want 3', async () => {
    // Exactly the same as the above...
  });
});

Testing Clerk's Official Next.js Integration @ app/api/authed

Suppose we created a new authenticated API endpoint at app/api/authed by cloning the Clerk App Router demo repo and following Clerk's quick-start guide for Next.js:

/* File: app/api/authed/route.ts */

import { auth } from '@clerk/nextjs';

export async function GET() {
  const { userId } = auth();
  return Response.json({ isAuthed: !!userId, userId });
}

How might we test that this endpoint functions as we expect?

/* File: test/unit.test.ts */

import { testApiHandler } from 'next-test-api-route-handler';
import * as appHandler from '../app/api/authed/route';

import type { auth } from '@clerk/nextjs';

let mockedClerkAuthReturnValue: Partial<ReturnType<typeof auth>> | undefined =
  undefined;

jest.mock('@clerk/nextjs', () => {
  return {
    auth() {
      return mockedClerkAuthReturnValue;
    }
  };
});

afterEach(() => {
  mockedClerkAuthReturnValue = undefined;
});

it('returns isAuthed: true and a userId when authenticated', async () => {
  expect.hasAssertions();

  mockedClerkAuthReturnValue = { userId: 'winning' };

  await testApiHandler({
    appHandler,
    test: async ({ fetch }) => {
      await expect((await fetch()).json()).resolves.toStrictEqual({
        isAuthed: true,
        userId: 'winning'
      });
    }
  });
});

it('returns isAuthed: false and nothing else when unauthenticated', async () => {
  expect.hasAssertions();

  mockedClerkAuthReturnValue = { userId: null };

  await testApiHandler({
    appHandler,
    test: async ({ fetch }) => {
      await expect((await fetch()).json()).resolves.toStrictEqual({
        isAuthed: false,
        userId: null
      });
    }
  });
});

If you're feeling more adventurous, you can transform this unit test into an integration test (like the Apollo example above) by calling Clerk's authMiddleware function in appHandler instead of mocking @clerk/nextjs:

// This integration test also requires your Clerk dashboard is setup in test
// mode and your Clerk secret key information is available in process.env. Said
// information must be available BEFORE any Clerk packages are imported! You
// will also have to setup authMiddleware properly in ../middleware.ts

/* ... same imports as before ... */
// Also import our Next.js middleware
import { default as middleware } from '../middleware';
// And we want to keep our types as tight as we can too
import type { NextRequest } from 'next/server';

const DUMMY_CLERK_USER_ID = 'user_2aqlGWnjdTRRbbBk9OdBHHbniyK';

it('returns isAuthed: true and a userId when authenticated', async () => {
  expect.hasAssertions();

  await testApiHandler({
    rejectOnHandlerError: true,
    // You may want to alter the default URL pathname like below if your Clerk
    // middleware is using path-based filtering. By default, the pathname
    // will always be '/' because 'ntarh://testApiHandler/' is the default url
    url: 'ntarh://app/api/authed',
    appHandler: {
      get GET() {
        return async function (...args: Parameters<typeof appHandler.GET>) {
          const request = args.at(0) as unknown as NextRequest;
          const middlewareResponse = await middleware(request, {
            /* ... */
          });

          // Make sure we're not being redirected to the sign in page since
          // this is a publicly available endpoint
          expect(middlewareResponse.headers.get('location')).toBeNull();
          expect(middlewareResponse.ok).toBe(true);

          const handlerResponse = await appHandler.GET(...args);

          // You could run some expectations here (since rejectOnHandlerError is
          // true), or you can run your remaining expectations in the test
          // function below. Either way is fine.

          return handlerResponse;
        };
      }
    },
    test: async ({ fetch }) => {
      await expect((await fetch()).json()).resolves.toStrictEqual({
        isAuthed: true,
        userId: DUMMY_CLERK_USER_ID
      });
    }
  });
});

/* ... */

You can also try calling authMiddleware in requestPatcher; however, Clerk's middleware does its magic by importing the headers helper function from 'next/headers', and only functions invoked within appHandler have access to the storage context that allows Next.js's helper functions to work. For insight into what you'd need to do to make authMiddleware callable in requestPatcher, check out Clerk's own tests.

Testing an Unreliable Handler on the Edge @ app/api/unreliable

Suppose we have an API endpoint we use to test our application's error handling. The endpoint responds with status code HTTP 200 for every request except the 10th, where status code HTTP 555 is returned instead.

How might we test that this endpoint responds with HTTP 555 once for every nine HTTP 200 responses?

/* File: test/unit.test.ts */

import { testApiHandler } from 'next-test-api-route-handler';
// Import the handler under test from the app/api directory
import * as edgeHandler from '../app/api/unreliable';

const expectedReqPerError = 10;

it('injects contrived errors at the required rate', async () => {
  expect.hasAssertions();

  // Signal to the edge endpoint (which is configurable) that there should be 1
  // error among every 10 requests
  process.env.REQUESTS_PER_CONTRIVED_ERROR = expectedReqPerError.toString();

  await testApiHandler({
    appHandler: edgeHandler,
    requestPatcher(request) {
      // Our edge handler expects Next.js to provide geo and ip data with the
      // request, so let's add some. This is also where you'd mock/emulate the
      // effects of any Next.js middleware
      return new NextRequest(request, {
        geo: { city: 'Chicago', country: 'United States' },
        ip: '110.10.77.7'
      });
    },
    test: async ({ fetch }) => {
      // Run 20 requests with REQUESTS_PER_CONTRIVED_ERROR = '10' and
      // record the results
      const results1 = await Promise.all(
        [
          ...Array.from({ length: expectedReqPerError - 1 }).map(() =>
            fetch({ method: 'GET' })
          ),
          fetch({ method: 'POST' }),
          ...Array.from({ length: expectedReqPerError - 1 }).map(() =>
            fetch({ method: 'PUT' })
          ),
          fetch({ method: 'DELETE' })
        ].map((p) => p.then((r) => r.status))
      );

      process.env.REQUESTS_PER_CONTRIVED_ERROR = '0';

      // Run 10 requests with REQUESTS_PER_CONTRIVED_ERROR = '0' and record the
      // results
      const results2 = await Promise.all(
        Array.from({ length: expectedReqPerError }).map(() =>
          fetch().then((r) => r.status)
        )
      );

      // We expect results1 to be an array with eighteen `200`s and two
      // `555`s in any order
      //
      // https://github.com/jest-community/jest-extended#toincludesamemembersmembers
      // because responses could be received out of order
      expect(results1).toIncludeSameMembers([
        ...Array.from({ length: expectedReqPerError - 1 }).map(() => 200),
        555,
        ...Array.from({ length: expectedReqPerError - 1 }).map(() => 200),
        555
      ]);

      // We expect results2 to be an array with ten `200`s
      expect(results2).toStrictEqual([
        ...Array.from({ length: expectedReqPerError }).map(() => 200)
      ]);
    }
  });
});

Using the Pages Router

These examples use Next.js's Pages Router API.

Testing Next.js's Official Apollo Example @ pages/api/graphql

This example uses the official Next.js Apollo demo. You can easily run it yourself by copying and pasting the following commands into your terminal.

The following should be run in a nix-like environment. On Windows, that's WSL. Requires curl, node, and git.

git clone --depth=1 https://github.com/vercel/next.js /tmp/ntarh-test
cd /tmp/ntarh-test/examples/api-routes-apollo-server-and-client
npm install --force
npm install --force next-test-api-route-handler jest babel-jest @babel/core @babel/preset-env
# You could test with an older version of Next.js if you want, e.g.:
# npm install --force [email protected]
# Or even older:
# npm install --force [email protected] next-server
echo 'module.exports={"presets":["next/babel"]};' > babel.config.js
mkdir test
curl -o test/integration.test.js https://raw.githubusercontent.com/Xunnamius/next-test-api-route-handler/main/apollo_test_raw
npx jest

This script clones the Next.js repository, installs NTARH and configures dependencies, downloads the jest test file shown below, and runs it using jest to ensure our route integrates with Apollo correctly.

Important

Note that passing the route configuration object (imported below as config) through to NTARH and setting request.url to the proper value may be necessary when testing Apollo endpoints using the Pages Router.

/* File: examples/api-routes-apollo-server-and-client/tests/integration.test.js */

import { testApiHandler } from 'next-test-api-route-handler';
// Import the handler under test from the pages/api directory
import * as pagesHandler from '../pages/api/graphql';

describe('my-test (pages router)', () => {
  it('does what I want 1', async () => {
    expect.hasAssertions();

    await testApiHandler({
      pagesHandler,
      url: '/api/graphql', // Set the request url to the path graphql expects
      test: async ({ fetch }) => {
        const query = `query ViewerQuery {
          viewer {
            id
            name
            status
          }
        }`;

        const res = await fetch({
          method: 'POST',
          headers: {
            'content-type': 'application/json' // Must use correct content type
          },
          body: JSON.stringify({ query })
        });

        await expect(res.json()).resolves.toStrictEqual({
          data: { viewer: { id: '1', name: 'John Smith', status: 'cached' } }
        });
      }
    });
  });

  it('does what I want 2', async () => {
    // Exactly the same as the above...
  });

  it('does what I want 3', async () => {
    // Exactly the same as the above...
  });
});

Testing an Authenticated Flight Search Handler @ pages/api/v3/flights/search

Suppose we have an authenticated API endpoint our application uses to search for flights. The endpoint responds with an array of flights satisfying the query.

How might we test that this endpoint returns flights in our database as expected?

/* File: test/unit.test.ts */

import { testApiHandler } from 'next-test-api-route-handler';
import { DUMMY_API_KEY as KEY, getFlightData, RESULT_SIZE } from '../backend';
import * as pagesHandler from '../pages/api/v3/flights/search';

import type { PageConfig } from 'next';

it('returns expected public flights with respect to match', async () => {
  expect.hasAssertions();

  // Get the flight data currently in the test database
  const expectedFlights = getFlightData();

  // Take any JSON object and stringify it into a URL-ready string
  const encode = (o: Record<string, unknown>) =>
    encodeURIComponent(JSON.stringify(o));

  // This function will return in order the URIs we're interested in testing
  // against our handler. Query strings are parsed by NTARH automatically.
  //
  // NOTE: setting the request url manually using encode(), while valid, is
  // unnecessary here; we could have used `params` or `paramsPatcher` to do this
  // more easily without explicitly setting a dummy request url.
  //
  // Example URI for `https://site.io/path?param=yes` would be `/path?param=yes`
  const genUrl = (function* () {
    // For example, the first should match all the flights from Spirit airlines!
    yield `/?match=${encode({ airline: 'Spirit' })}`;
    yield `/?match=${encode({ type: 'departure' })}`;
    yield `/?match=${encode({ landingAt: 'F1A' })}`;
    yield `/?match=${encode({ seatPrice: 500 })}`;
    yield `/?match=${encode({ seatPrice: { $gt: 500 } })}`;
    yield `/?match=${encode({ seatPrice: { $gte: 500 } })}`;
    yield `/?match=${encode({ seatPrice: { $lt: 500 } })}`;
    yield `/?match=${encode({ seatPrice: { $lte: 500 } })}`;
  })();

  await testApiHandler({
    // Patch the request object to include our dummy URI
    requestPatcher: (req) => {
      req.url = genUrl.next().value || undefined;
      // Could have done this instead of `fetch({ headers: { KEY }})` below:
      // req.headers = { KEY };
    },

    pagesHandler,

    test: async ({ fetch }) => {
      // 8 URLs from genUrl means 8 calls to fetch:
      const responses = await Promise.all(
        Array.from({ length: 8 }).map(() =>
          fetch({ headers: { KEY } }).then(async (r) => [
            r.status,
            await r.json()
          ])
        )
      );

      // We expect all of the responses to be 200
      expect(responses.some(([status]) => status !== 200)).toBe(false);

      // We expect the array of flights returned to match our
      // expectations given we already know what dummy data will be
      // returned:

      // https://github.com/jest-community/jest-extended#toincludesamemembersmembers
      // because responses could be received out of order
      expect(responses.map(([, r]) => r.flights)).toIncludeSameMembers([
        expectedFlights
          .filter((f) => f.airline === 'Spirit')
          .slice(0, RESULT_SIZE),
        expectedFlights
          .filter((f) => f.type === 'departure')
          .slice(0, RESULT_SIZE),
        expectedFlights
          .filter((f) => f.landingAt === 'F1A')
          .slice(0, RESULT_SIZE),
        expectedFlights
          .filter((f) => f.seatPrice === 500)
          .slice(0, RESULT_SIZE),
        expectedFlights.filter((f) => f.seatPrice > 500).slice(0, RESULT_SIZE),
        expectedFlights.filter((f) => f.seatPrice >= 500).slice(0, RESULT_SIZE),
        expectedFlights.filter((f) => f.seatPrice < 500).slice(0, RESULT_SIZE),
        expectedFlights.filter((f) => f.seatPrice <= 500).slice(0, RESULT_SIZE)
      ]);
    }
  });

  // We expect these two to fail with 400 errors

  await testApiHandler({
    pagesHandler,
    url: `/?match=${encode({ ffms: { $eq: 500 } })}`,
    test: async ({ fetch }) =>
      expect((await fetch({ headers: { KEY } })).status).toBe(400)
  });

  await testApiHandler({
    pagesHandler,
    url: `/?match=${encode({ bad: 500 })}`,
    test: async ({ fetch }) =>
      expect((await fetch({ headers: { KEY } })).status).toBe(400)
  });
});

Testing an Unreliable Handler @ pages/api/unreliable

Suppose we have an API endpoint we use to test our application's error handling. The endpoint responds with status code HTTP 200 for every request except the 10th, where status code HTTP 555 is returned instead.

How might we test that this endpoint responds with HTTP 555 once for every nine HTTP 200 responses?

/* File: test/unit.test.ts */

import { testApiHandler } from 'next-test-api-route-handler';
// Import the handler under test from the pages/api directory
import * as pagesHandler from '../pages/api/unreliable';

const expectedReqPerError = 10;

it('injects contrived errors at the required rate', async () => {
  expect.hasAssertions();

  // Signal to the endpoint (which is configurable) that there should be 1
  // error among every 10 requests
  process.env.REQUESTS_PER_CONTRIVED_ERROR = expectedReqPerError.toString();

  await testApiHandler({
    pagesHandler,
    test: async ({ fetch }) => {
      // Run 20 requests with REQUESTS_PER_CONTRIVED_ERROR = '10' and
      // record the results
      const results1 = await Promise.all(
        [
          ...Array.from({ length: expectedReqPerError - 1 }).map(() =>
            fetch({ method: 'GET' })
          ),
          fetch({ method: 'POST' }),
          ...Array.from({ length: expectedReqPerError - 1 }).map(() =>
            fetch({ method: 'PUT' })
          ),
          fetch({ method: 'DELETE' })
        ].map((p) => p.then((r) => r.status))
      );

      process.env.REQUESTS_PER_CONTRIVED_ERROR = '0';

      // Run 10 requests with REQUESTS_PER_CONTRIVED_ERROR = '0' and record the
      // results
      const results2 = await Promise.all(
        Array.from({ length: expectedReqPerError }).map(() =>
          fetch().then((r) => r.status)
        )
      );

      // We expect results1 to be an array with eighteen `200`s and two
      // `555`s in any order
      //
      // https://github.com/jest-community/jest-extended#toincludesamemembersmembers
      // because responses could be received out of order
      expect(results1).toIncludeSameMembers([
        ...Array.from({ length: expectedReqPerError - 1 }).map(() => 200),
        555,
        ...Array.from({ length: expectedReqPerError - 1 }).map(() => 200),
        555
      ]);

      // We expect results2 to be an array with ten `200`s
      expect(results2).toStrictEqual([
        ...Array.from({ length: expectedReqPerError }).map(() => 200)
      ]);
    }
  });
});

Appendix

Further documentation can be found under docs/.

Limitations with App Router and Edge Runtime Emulation

Since NTARH is meant for unit testing API routes rather than faithfully recreating Next.js functionality, NTARH's feature set comes with some caveats. Namely: no Next.js features will be available that are external to processing API routes and executing their handlers. This includes middleware and NextResponse.next (see requestPatcher if you need to mutate the Request before it gets to the handler under test), metadata, static assets, OpenTelemetry and instrumentation, caching, styling, server actions and mutations, helper functions (except: cookies, fetch (global), headers, NextRequest, NextResponse, notFound, permanentRedirect, redirect, and userAgent), and anything related to React or components.

NTARH is for testing your API route handlers only.

Further, any support NTARH appears to have for any "edge runtime" (or any other runtime) beyond what is provided by AppRouteRouteModule is merely cosmetic. Your tests will always run in Node.js (or your runner of choice) and never in a different runtime, realm, or VM. This means unit testing like with NTARH must be done in addition to, and not in lieu of, more holistic testing practices (e.g. end-to-end).

If you're having trouble with your App Router and/or Edge Runtime routes, consider opening a new issue!

Also note that Next.js's middleware only supports the Edge runtime, even if the Next.js application is being run entirely by Node.js. This is an artificial constraint imposed by Next.js; when running the middleware locally (via npm run dev or something similar), the middleware will still run on Node.js.

Next.js's middleware limitation is discussed at length here.

Working around the App Router Patching the Global fetch Function

Next.js's current App Router implementation mutates the global fetch function, redefining it entirely. This can cause problems in testing environments where the global fetch is to be mocked by something else.

Internally, NTARH sidesteps this issue entirely by caching the value of globalThis.fetch upon import. This also means NTARH completely sidesteps other tools that rely on interception through rewriting the global fetch function, such as Mock Service Worker (MSW). We still include the MSW bypass headers with NTARH requests since we cannot guarantee that NTARH will not be imported after MSW has finished patching global fetch.

Similarly, it is impossible for NTARH to meaningfully track mutations to the global fetch function; NTARH cannot tell the difference between Next.js overwriting fetch and, say, a Jest spy overwriting fetch. Therefore, NTARH does not restore the cached fetch after the function returns.

If Next.js's patching of fetch is causing trouble for you, you can do what NTARH does: capture the current global fetch (perhaps after setting up MSW) and then restore it after each test:

const originalGlobalFetch = fetch;

afterEach(function () {
  // Undo what Next.js does to the global fetch function
  globalThis.fetch = originalGlobalFetch;
});

Working around Global AsyncLocalStorage Availability

AppRouteRouteModule and its dependents want AsyncLocalStorage to be available globally and immediately. Unfortunately, Node.js does not place AsyncLocalStorage in globalThis natively.

NTARH handles this by ensuring AsyncLocalStorage is added to globalThis before Next.js needs it. This is why NTARH should always be the very first import in any test file.

Legacy Runtime Support

As of version 4.0.0, NTARH supports both the App Router (for next@>=14.0.4) and the "legacy" Pages Router Next.js APIs. However, due to the code churn with next@13, NTARH's support for the App Router begins at [email protected]. See here and here for more information.

Additionally, as of version 2.1.0, NTARH's Pages Router support is fully backwards compatible with Next.js going allll the way back to [email protected] when API routes were first introduced!

If you're working with the Pages Router and next@<9.0.6 (so: before next-server was merged into next), you might need to install next-server manually:

npm install --save-dev next-server

Similarly, if you are using npm@<7 or node@<15, you must install Next.js and its peer dependencies manually. This is because npm@<7 does not install peer dependencies by default.

npm install --save-dev next@latest react

If you're also using an older version of Next.js, ensure you install the peer dependencies (like react) that your specific Next.js version requires!

Jsdom Support

Note that jsdom does not support global fetch natively. This should not be an issue, however, since neither your API code nor your API test code should be executed in a browser-like environment.

For projects configured to use jsdom by default, you can use an annotation to switch environments only in the files housing your API tests:

/**
 * @jest-environment node
 */
// ⬆⬆⬆⬆⬆⬆⬆⬆⬆⬆⬆⬆⬆

import { testApiHandler } from 'next-test-api-route-handler';

test('use the node test environment for all tests in this file', () => {
  //...
});

If you're dead set on using jsdom over the node testing environment with NTARH, see here and here for workarounds.

Inspiration

I'm constantly creating things with Next.js. Most of these applications have a major API component. Unfortunately, Next.js doesn't make unit testing your APIs very easy. After a while, I noticed some conventions forming around how I liked to test my APIs and NTARH was born 🙂

Of course, this all was back before the app router or edge routes existed. NTARH got app router and edge route support in version 4.

My hope is that NTARH gets obsoleted because Vercel provided developers with some officially supported tooling/hooks for lightweight route execution where handlers are passed fully initialized instances of NextRequest/NextResponse/NextApiRequest/NextApiResponse without ballooning the execution time of the tests. That is: no spinning up the entire Next.js runtime just to run a single test in isolation.

It doesn't seem like it'd be such a lift to surface a wrapped version of the Pages Router's apiResolver function and a pared-down subclass of the App Router's AppRouteRouteModule, both accessible with something like import { ... } from 'next/test'. This is essentially what NTARH does.

Published Package Details

This is a CJS2 package with statically-analyzable exports built by Babel for Node.js versions that are not end-of-life. For TypeScript users, this package supports both "Node10" and "Node16" module resolution strategies.

Expand details

That means both CJS2 (via require(...)) and ESM (via import { ... } from ... or await import(...)) source will load this package from the same entry points when using Node. This has several benefits, the foremost being: less code shipped/smaller package size, avoiding dual package hazard entirely, distributables are not packed/bundled/uglified, a drastically less complex build process, and CJS consumers aren't shafted.

Each entry point (i.e. ENTRY) in package.json's exports[ENTRY] object includes one or more export conditions. These entries may or may not include: an exports[ENTRY].types condition pointing to a type declarations file for TypeScript and IDEs, an exports[ENTRY].module condition pointing to (usually ESM) source for Webpack/Rollup, an exports[ENTRY].node condition pointing to (usually CJS2) source for Node.js require and import, an exports[ENTRY].default condition pointing to source for browsers and other environments, and other conditions not enumerated here. Check the package.json file to see which export conditions are supported.

Though package.json includes { "type": "commonjs" }, note that any ESM-only entry points will be ES module (.mjs) files. Finally, package.json also includes the sideEffects key, which is false for optimal tree shaking where appropriate.

License

See LICENSE.

Contributing and Support

New issues and pull requests are always welcome and greatly appreciated! 🤩 Just as well, you can star 🌟 this project to let me know you found it useful! ✊🏿 Or you could buy me a beer 🥺 Thank you!

See CONTRIBUTING.md and SUPPORT.md for more information.

Contributors

All Contributors

Thanks goes to these wonderful people (emoji key):

Bernard
Bernard

🚇 💻 📖 🚧 ⚠️ 👀
Kevin Jennison
Kevin Jennison

📖
jonkers3
jonkers3

📖
Valentin Hervieu
Valentin Hervieu

💻 🤔 🔬 ⚠️
Dana Woodman
Dana Woodman

🚇
Rhys
Rhys

🤔
Prakhar Shukla
Prakhar Shukla

🐛
Jake Jones
Jake Jones

🐛 🤔 🔬
Diego Esclapez
Diego Esclapez

🐛
k2xl
k2xl

🔬
Jeremy Walker
Jeremy Walker

💡
Adrian Kriegel
Adrian Kriegel

💡
hems.io
hems.io

🐛 🔬 🤔 💡
Steve Taylor
Steve Taylor

🤔
Will Nixon
Will Nixon

🐛 🔬
Sebastien Powell
Sebastien Powell

💡
Hajin Lim
Hajin Lim

🤔
Jane
Jane

💡
Jan Hesters
Jan Hesters

🐛
Bence Somogyi
Bence Somogyi

🐛 💻 🔬 ⚠️
Tony
Tony

🔬
Jaakko Jokinen
Jaakko Jokinen

🐛 🔬 🤔
Arun Sathiya
Arun Sathiya

🔬 💻
Scott Symmank
Scott Symmank

🔬 🐛
Matias De Carli
Matias De Carli

📖
Xing Xiang
Xing Xiang

📖
Kaarle Järvinen
Kaarle Järvinen

🐛
Rory Ou
Rory Ou

🐛 🔬 📖
Shinji Nakamatsu
Shinji Nakamatsu

📖 🐛 🔬
David Mytton
David Mytton

🔬 🐛 🔣
Dan BROOKS
Dan BROOKS

📖
Add your contributions

This project follows the all-contributors specification. Contributions of any kind welcome!

next-test-api-route-handler's People

Contributors

arunsathiya avatar danawoodman avatar dependabot[bot] avatar jonkers3 avatar kmjennison avatar matiasdecarli avatar valentinh avatar xunn-bot avatar xunnamius avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

next-test-api-route-handler's Issues

Jest did not exit one second after the test run has completed.

i am looking for a nice way to unit test my route handlers.
many thanks for this package.

when using the appHandler, there seems to be an open promise after my tests complete: Jest did not exit one second after the test run has completed.

is this expected behavior, or am i perhaps missing some sort of tear down call ?

Jest --detectOpenHandles

  ●  TCPWRAP

      4 | describe('POST() route', () => {
      5 |   it('FOO', async () => {
    > 6 |     await testApiHandler({
        |                         ^
      7 |       appHandler,
      8 |       async test({ fetch }) {
      9 |         const result = await fetch({ method: 'POST', body: 'dummy-data' });

      at port (../../node_modules/.pnpm/[email protected][email protected]/node_modules/next-test-api-route-handler/dist/src/index.js:121:15)
      at testApiHandler (../../node_modules/.pnpm/[email protected][email protected]/node_modules/next-test-api-route-handler/dist/src/index.js:120:24)
      at Object.<anonymous> (app/match/organizations/_tests/POST.route.test.ts:6:25)

My route and test

import { NextRequest, NextResponse } from 'next/server';
export async function POST(request: NextRequest) {
  return NextResponse.json({
    received: true,
  });
import { testApiHandler } from 'next-test-api-route-handler';
import * as appHandler from '../route';

describe('POST() route', () => {
  it('test()', async () => {
    await testApiHandler({
      appHandler,
      async test({ fetch }) {
        const result = await fetch({ method: 'POST', body: 'foo' });
        await expect(result.json()).resolves.toStrictEqual({ received: true });
      },
    });
  });
});

Steps To Reproduce using next-test-api-route-handler repo

  • it seems like the repo unit tests also demonstrate it
next-test-api-route-handler on  main is 📦 4.0.2 via ⬢ v18.17.1 took 24.8s 
➜ npm test

> [email protected] test
> npm run test:unit --


> [email protected] test:unit
> NODE_OPTIONS='--no-warnings' NODE_ENV=test jest '/unit-.*\.test\.tsx?' --testPathIgnorePatterns '/dist/'

 PASS  test/unit-index-imports.test.ts
 PASS  test/unit-msw.test.ts
 PASS  test/unit-external.test.ts
 PASS  test/unit-index.test.ts
A worker process has failed to exit gracefully and has been force exited. This is likely caused by tests leaking due to improper teardown. Try running with --detectOpenHandles to find leaks. Active timers can also cause this, ensure that .unref() was called on them.

Test Suites: 4 passed, 4 total
Tests:       93 passed, 93 total
Snapshots:   0 total
Time:        1.821 s
Ran all test suites matching /\/unit-.*\.test\.tsx?/i.

Expose function callbacks to TestApiClient instance in next major version

The solution

I think these test, requestPatcher and responsePatcher functions are unnecessary to be defined when creating tester instance. It's so limited when we need to create tester with some options dynamically and asynchronous work with Promises is better than callbacks. So, to avoid dirty codes caused by callbacks, it can be solved by exposing these functions like setting headers to be setted after the testApiHandler instance is created.

Example:

const api = require("../../pages/api/someApiEndpoint")
const { TestApiClient } = require("next-test-api-route-handler")

// as class instance:
const tester = new TestApiClient({ handler: api })
// as function:
const tester = TestApiClient({ handler: api })

// Proposal 1: defining directly
tester.request.headers = { key: process.env.SPECIAL_TOKEN }
// Proposal 2: exposing 'setXXX' functions 
tester.request.setHeader('key', process.env.SPECIAL_TOKEN)

const example = await tester.fetch({ method: 'GET' }).then(r => r.json())

// test with test environments like jest
expect(example).toBe('test')

// Block tentative after test was already executed
tester.request.setHeader('test', 'error')
// Error: cannot set header after test was already executed

Alternatives considered

I'm open to other suggestions, but if you dont want to expose everything because there are too many codes to be edited, you can only expose the test function and this will help me a lot.

Additional context

Issue with Apollo Server API (404 Error and no JSON Fetching work)

Problematic behavior

I created an API that serves an Apollo-Server with an Query. When I test it with your library it returns 404 Not Found and I can't access the Response Data json without invalid json error.

await testApiHandler({
    requestPatcher: (req) => {
      req.headers = {
        ...req.headers,
        Origin: "localhost:3000",
        Host: "localhost:3000",
      };
    },
    handler: graphQlHandler,
    test: async ({ fetch }) => {
      const query = `query getYoutubeVideoMetadata($youtubeVideoId: String!) {
  videoData: youtubeVideoMeadata(youtubeVideoId: $youtubeVideoId) {
    id
    title
    thumbnails {
      default {
        url
      }
    }
  }
}
`;
      const res = await fetch({
        method: "POST",
        headers: {
          Accept: "	*/*",
          "Accept-Encoding":
            "gzip deflate",
          "Accept-Language":
            "de,en-US;q=0.7,en;q=0.3",
          "Content-Type":
            "application/json",
          "User-Agent":
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:85.0) Gecko/20100101 Firefox/85.0",
        },
        body: JSON.stringify({
          operationName:
            "getYoutubeVideoMetadata",
          query,
          variables: {
            youtubeVideoId: exampleYoutubeVideoId,
          },
        }),
      });
      console.log(await res.json());
    },
  });
Expected behavior
Reproduction steps
  1. Start Jest Test against API.
  2. Return JSOnN Data from Query.
  3. Successful Resolve them and get 200 or so.
Runtime environment
  • OS: windows/mac os
  • Browser: firefox 71, chrome 90
  • Version: v1.2.3
  • Node version: 14
  • Babel: yes, version 7
  • TypeScript project: yes
Additional context

Add response.cookies field for easier access to multiple cookies

The problem

When testing a Next.js API route that sets multiple cookies, only the most recent Set-Cookie header is detected.

Reproduction steps

Clone this repo and run the test (instructions in README.md).

The test is expected to fail due to this bug. (However, I don't know what a pass looks like, as multiple cookies are encoded in a different way than other headers.)

Suggested solution

As this is partially caused by a deficiency in the fetch API, consider adding a cookies field to the response, so we can do something like this:

import {serialize} from 'cookie'
import {testApiHandler} from 'next-test-api-route-handler'

describe('next-test-api-route-handler bug', () => {
    it('is a bug', async () => {
        await testApiHandler({
            handler: async (_req, res) => {
                res.setHeader('Set-Cookie', serialize('access_token', '1234'))
                res.setHeader('Set-Cookie', serialize('refresh_token', '5678'))
                res.status(204).end()
            },
            test: async ({fetch}) => {
                const response = await fetch({
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({})
                })

                // Test hypothetical cookies property
                expect(response.cookies.sort()).toEqual([
                    'access_token=1234',
                    'refresh_token=5678',
                ])
            },
        })
    })
})

Vercel lambda governing compatibility badge isn't tracking latest compat version anymore

The problem

Maybe it's just that the caches near my usual internet access points are stale, but it appears the endpoint responsible for updating the compat info badge is no longer doing its job (still at 14.0.1 when next is at 14.0.4). The Actions tests all pass, so NTARH still works.

First guess: API change at shields.io. Second guess: GitHub's own image caching solution broke. Will investigate when I come back around to finish app router compat feature in a little bit. Nope. As usual, it was just my fault (shot myself in the foot with tee again).

ValidationPipe not triggering in unit tests

The problem

When running a unit test using Jest the validation pipeline is not triggered. The expected behaviour would be by providing incorrect values to a route which accepts a body that the validation pipe would be triggered and an error returned to the client.

// The input model
import { IsNumber, IsNotEmpty, IsString, IsOptional } from 'class-validator';

export class UpdateAlbumInputModel {
  @IsNotEmpty()
  @IsNumber()
  albumId: number;
  @IsOptional()
  @IsString()
  description?: string;
  @IsNotEmpty()
  @IsString()
  name: string
}

// The route
@Put('/albums')
@HttpCode(204)
public async updateAlbums(
  @Body(ValidationPipe) body: UpdateAlbumInputModel
) {
  return await this.albumService.updateAlbums(body);
}

The unit test can be found here:

it('should fail to update albums, if the body is invalid', async () => {
  await testApiHandler({
    handler: albumHandler,
    url: '/api/albums',
    test: async ({ fetch }) => {
      const res = await fetch({
        method: 'PUT',
        body: JSON.stringify({
          description: 'description',
        }),
        headers: {
          'Content-Type': 'application/json',
        },
      });
      // This returns a 204 status code, but expected to return an invalid status code of 400 (Bad Request)
      console.log(res);
    },
  });
});
Additional context
Response {
        size: 0,
        timeout: 0,
        cookies: [Getter],
        [Symbol(Body internals)]: {
          body: PassThrough {
            _readableState: [ReadableState],
            _events: [Object: null prototype],
            _eventsCount: 2,
            _maxListeners: undefined,
            _writableState: [WritableState],
            allowHalfOpen: true,
            [Symbol(kCapture)]: false,
            [Symbol(kCallback)]: null
          },
          disturbed: false,
          error: null
        },
        [Symbol(Response internals)]: {
          url: 'http://localhost:53325/',
          status: 204,
          statusText: 'No Content',
          headers: Headers { [Symbol(map)]: [Object: null prototype] },
          counter: 0
        }
      }

Package versions:
"class-transformer": "0.5.1",
"class-validator": "0.14.0",
"next-api-decorators": "2.0.2",

Module not found: Can't resolve 'next/dist/next-server/server/api-utils.js' in '.../node_modules/next-test-api-route-handler/dist/esm'

The problem

Just updated next.js to version 12 and now the project build is failing.

Curiously the tests are still passing, but "next build" fails with the following error:

$ next build --debug
 ******* next.config.js building:
            NODE_ENV: production
                 ENV: localhost
info  - Checking validity of types...
warn  - The Next.js plugin was not detected in your ESLint configuration. See https://nextjs.org/docs/basic-features/eslint#migrating-existing-config
info  - Creating an optimized production build...
warn  - Disabled SWC as replacement for Babel because of custom Babel configuration ".babelrc" https://nextjs.org/docs/messages/swc-disabled
info  - Using external babel configuration from /home/runner/my-project/.babelrc
Failed to compile.

./node_modules/next-test-api-route-handler/dist/esm/index.mjs
Module not found: Can't resolve 'next/dist/next-server/server/api-utils.js' in '/home/runner/my-project/node_modules/next-test-api-route-handler/dist/esm'

Import trace for requested module:
./src/pages/api/my-endpoint.test.ts

./node_modules/next-test-api-route-handler/dist/esm/index.mjs
Module not found: Can't resolve 'next-server/dist/server/api-utils.js' in '/home/runner/my-project/node_modules/next-test-api-route-handler/dist/esm'

Import trace for requested module:
./src/pages/api/my-endpoint.test.ts
Reproduction steps

I guess you just need to create a test and import next-test-api-route-handler, like this:

import { testApiHandler } from 'next-test-api-route-handler'

and then run next build.

Additional context
  • OS: OSX
  • Node version: 12.22.7

TypeError: Only absolute URLs are supported

Problematic behavior I've tried setting this up as explained in the docs. When I try running the test suite, my test fails with the message `TypeError: Only absolute URLs are supported`
Reproduction steps Here's what my code looks like: Screenshot 2021-08-22 at 09 01 19

I tried setting an absolute URL (e.g. http://localhost:3000/pages/api/me), but that didn't work. I also tried removing 'pages' (e.g. /api/me), and no luck there either.

I'm using the Next.js runtime, so my /api directory is inside /pages. So I tried switching to a Node.js runtime by moving the /api directory to the root folder, but no luck there either.

I may have missed something in the docs, but can't see it – this looks like a great, and much needed package, so would love to get this working!

Expected behavior I would expect to be able to run the test suite.

Doesn't work in node 20.8.0 to 20.x

The problem

In a project using node 20.8+ (20.8.0, 20.8.1, 20.9.0...), using node 20 as major, minor 8 and up. Gives the following error:

Error: next-test-api-route-handler (NTARH) failed to import api-utils.js

  This is usually caused by:

    1. Using npm@<7 and/or node@<15, which doesn't install peer deps automatically (review install instructions)
    2. NTARH and the version of Next.js you installed are actually incompatible (please submit a bug report)

  Failed import attempts:

    - EBADF: bad file descriptor, fstat
    - Cannot find module 'next/dist/server/api-utils.js'
    - Cannot find module 'next/dist/next-server/server/api-utils.js'
    - Cannot find module 'next-server/dist/server/api-utils.js'

    at y (/<repo_path>/node_modules/next-test-api-route-handler/dist/index.js:71:38)
    at async Object.<anonymous> (<repo_path>/src/modules/portal/api/downloadExamPdf.test.ts:44:5)

I didn't try in other OS, just Macosx Ventura.

Seems working with no problem in 20.7.0

Reproduction steps In a basic next project, using jest and next-test-api-route-handler:
  • With node 20.8.0 execute an api handler test
Additional context
  • OS: Macosx Ventura
  • Node version: 20.8.0
  • TypeScript: yes, version 5.2.0

Relevant log lines:

(super long error log lines pasted here)

Compat issue with [email protected]

Problematic behavior

WIth 11.1.0, the Next.js devs moved api-utils.js to a slightly different path. Canary build already has a working fix, will push release momentarily. This version of NTARH will be backwards compatible with all versions of Next.js >= 10.0.0.

Enhancement: subsequent versions of NTARH will use the same technique to enable backwards compatibility with next going back to 9.0.0 (a little trickier)!

Reproduction steps
Expected behavior
Additional context

stack trace from error on `test` function?

I been testing a route that was failing due to a problem with axios and i was getting a SyntaxError from inside of axios but i couldn't figure out where the error was coming from because it seems next-test-api-router-handler was throwing only a string and not the entire error / stack trace?

image

The solution

throw the entire error with stack trace when an error happen? Would that possible or is that a limitation from apiResolver?

That would help a lot when debugging errors on tests!

Thanks for your help / library

Test file-uploading API Endpoint

I just discovered this library, and it seems to be exactly what I need, except ... I need to test a file-upload API, and I couldn't find any examples in the documentation of testing such endpoints.

Is it possible, and if so are there any examples or docs I can reference?

Potential NTARH incompatibility with `next/jest.js`

As discussed in #983.

Seems next/jest.js calls some sort of internal environmental setup function for http/https "agents" that ends up changing the nature of the Request object; specifically: spreading the Request object functions differently. This occurs when calling nextJest in const createJestConfig = nextJest({ dir: './' }) where nextJest is defined as import nextJest from 'next/jest.js'. When the dir option is omitted, the discussed error does not occur.

Drilling into what the function returned by calling createJestConfig in const jestConfig = await createJestConfig(config)() is actually doing, we get the following stack:

const jestConfig = await createJestConfig(config)()
const createJestConfig = nextJest({
  // Provide the path to your Next.js app to load next.config.js and .env files in your test environment
  dir: './'
});
function nextJest(options = {}) {
    // createJestConfig
    return (customJestConfig)=>{
        // Function that is provided as the module.exports of jest.config.js
        // Will be called and awaited by Jest
        return async ()=>{
...
            if (options.dir) {
                const resolvedDir = (0, _path.resolve)(options.dir);
                const packageConfig = loadClosestPackageJson(resolvedDir);
                isEsmProject = packageConfig.type === "module";
                nextConfig = await getConfig(resolvedDir);
...
async function getConfig(dir) {
    const conf = await (0, _config.default)(_constants.PHASE_TEST, dir);
    return conf;
}
// Is the "default" export of "config"
async function loadConfig(phase, dir, { customConfig, rawConfig, silent = true, onLoadUserConfig } = {}) {
...
assignDefaults(dir, ...)
..
function assignDefaults(dir, userConfig, silent) {
...
(0, _setuphttpagentenv.setHttpClientAndAgentOptions)(result || _configshared.defaultConfig);
...

This is the function that, once executed, somehow subtly changes what @whatwg-node/server's createServerAdapter() returns:

function setHttpClientAndAgentOptions(config) {
    if (globalThis.__NEXT_HTTP_AGENT) {
        // We only need to assign once because we want
        // to reuse the same agent for all requests.
        return;
    }
    if (!config) {
        throw new Error("Expected config.httpAgentOptions to be an object");
    }
    globalThis.__NEXT_HTTP_AGENT_OPTIONS = config.httpAgentOptions;
    globalThis.__NEXT_HTTP_AGENT = new _http.Agent(config.httpAgentOptions);
    globalThis.__NEXT_HTTPS_AGENT = new _https.Agent(config.httpAgentOptions);
}

Rather than investigate this further, it seems whatever is going on is not really an NTARH issue. The solution here is to just explicitly declare/reference each valid property in the Request constructor's options parameter instead of trying to spread the Request instance to grab its properties.

npm package size is very large

I'm seeing 121mb in my node_modules which is larger than my next package:

121M	/app/node_modules/next-test-api-route-handler
103M	/app/node_modules/next

Any way that you could ignore content using the .npmignore file?

Status always 200 on redirect.

Problem

I think the title is self-explanatory. Status appears to be 200 in any case.

Reproduction steps Jest example:
import { testApiHandler } from 'next-test-api-route-handler';

test('redirect', async () => 
{
  await testApiHandler(
    {
      handler: (req, res) => res.redirect(307, 'https://example.com'),
      test: async ({ fetch }) => 
      {
        const res = await fetch();
        // this fails, status is 200
        expect(res.status).toBe(307);
      },
    },
  );
});

Relative URL doesn't work with appHandler: "Invalid URL" error

The problem

It seems this commit about normalization of URLs may have broken the ability to use a relative-style url param with the app handler because calling new URL(url) on a path like "/my-url" throws Invalid URL error (as one would expect it to, since new URL() doesn't accept relative URLs).

    TypeError: Invalid URL

      at normalizeUrlForceTrailingSlashIfPathnameEmpty (node_modules/.pnpm/next-test-api-route-handler@4.
[email protected]/node_modules/next-test-api-route-handler/dist/src/index.js:337:16)

I was able to get around this easily by providing a dummy beginning of the url as the tests do (e.g. "ntarh://api/books" instead of just "/api/books"), but it doesn't match what the docs say, so it required some digging to figure this out.

I noticed the tests include a case with url: '/my-url' and pagesHandler, but not a case for the same url with appHandler. I believe that's the case that's broken.

Reproduction steps
  1. Run a basic example like:
it("works", async () => {
  await testApiHandler({
    appHandler,
    url: "/my-url",
    async test({ fetch }) {
      const res = await fetch({
        method: "GET",
      })

      const json = await res.json()

      expect(json).toStrictEqual([])
    },
  })
})

originalGlobalFetch is not a function

The problem

I tried NTARH v4.0.5 with Next.js v14.1.4 or v14.2.1 and my unit tests fail with this reason:
originalGlobalFetch is not a function

Sample unit test that fails

import { testApiHandler } from 'next-test-api-route-handler'

test('Sample test that fails on line 8', async () => {
  await testApiHandler({
    params: { id: 5 },
    pagesHandler: (req, res) => res.status(200).send({ id: req.query.id }),
    test: async ({ fetch }) =>
      expect((await fetch({ method: 'POST' })).json()).resolves.toStrictEqual({
        id: 5
      })
  });
})
Reproduction steps
  1. Clone the history repo I made: https://github.com/danactive/history/tree/update-deps
  2. nvm use Match node.js version
  3. npm ci Install deps
  4. npm test Run test suite
  5. See error "originalGlobalFetch is not a function" at test "Gallery endpoint › Expect result › * GET has gallery", which shouldn't be happening
Expected behavior
  1. Clone the history repo I made: https://github.com/danactive/history/tree/update-deps
  2. nvm use Match node.js version
  3. npm ci Install deps
  4. npm test Run test suite
  5. All tests should pass
Additional context
  • OS: macos Sonoma 14.3
  • Node version: 20
  • Babel: No
  • TypeScript: yes, version 5.2.2
  • Browser: N/A using Node.js CLI
  • List of installed packages

Error: Invariant: Method expects to have requestAsyncStorage, none available

Error: Invariant: Method expects to have requestAsyncStorage, none available

Hey! I am trying to test my app route handlers which are protected using Clerk.dev authentication.
When testing an endpoint which is not protected with clerk the test runs fine but as soon as an endpoint protected with clerk is tested it throws the following error:

 Error: Clerk: auth() and currentUser() are only supported in App Router (/app directory).
@acme/admin:test:       If you're using /pages, try getAuth() instead.
@acme/admin:test:       Original error: Error: Invariant: Method expects to have requestAsyncStorage, none available
Reproduction steps
  1. Create a basic next app and install clerk following the guide at https://clerk.com/docs
  2. Now try to create a test that tests a protected route, e.g:
import type { PageConfig } from "next";
import { testApiHandler } from "next-test-api-route-handler";

import {
  GET as getReqAdmin,
  PUT as putReqAdmin,
} from "../../app/api/admin/route";
import { prisma } from "../../lib/prismaClient";
import { orderSeedData, userSeedData } from "../testUtils/seedData";

beforeEach(async () => {
  await prisma.users.create({
    data: userSeedData,
  });
  await prisma.orders.create({
    data: orderSeedData,
  });
});

afterEach(async () => {
  await prisma.users.deleteMany();
  await prisma.users.deleteMany();
});

// Respect the Next.js config object if it's exported
const getReqHandler: typeof getReqAdmin & { config?: PageConfig } = getReqAdmin;
const putReqHandler: typeof putReqAdmin & { config?: PageConfig } = putReqAdmin;

describe("admin api", () => {
  it("should return 401 unauthorized", async () => {
    await testApiHandler({
      handler: getReqHandler,
      test: async ({ fetch }) => {
        const res = await fetch({ method: "GET" });
        await expect(res.status).resolves.toStrictEqual(401);
      },
    });
  });
});

Expected behavior

The test should pass since the library states that it is compatible with the app router.

Additional context

System:
OS: macOS 13.2.1
CPU: (8) arm64 Apple M1
Memory: 159.31 MB / 16.00 GB
Shell: 5.8.1 - /bin/zsh
Binaries:
Node: 16.20.2 - /opt/homebrew/opt/node@16/bin/node
Yarn: 1.22.17 - ~/.yarn/bin/yarn
npm: 9.8.1 - ~/temp_turbo_order//node_modules/.bin/npm
pnpm: 8.5.1 - ~/Library/pnpm/pnpm

next-test-api-route-handler (NTARH) failed to import api-utils.js

When running npm test I see:

 next-test-api-route-handler (NTARH) failed to import api-utils.js

      This is usually caused by:

        1. Using npm@<7 and/or node@<15, which doesn't install peer deps automatically (review install instructions)
        2. NTARH and the version of Next.js you installed are actually incompatible (please submit a bug report)

      Failed import attempts:

node -v shows v16.20.0
npm -v shows 9.8.1

I'm on Mac OSX using jest. I've tried rm -rf the node_modules and reinstalling but still getting this error.

Bypassing MSW does not work with MSW 2.X

This is more of a FYI.

In version 3.1.0, the x-msw-bypass header was introduced in order to have better out of the box support for MSW.

MSW released a new version two weeks ago. Version 2.0 no longer respects the x-msw-bypass header. It seems that this header was considered to be an implementation detail as it's not documented as a breaking change.

MSW 2.0 has a new utility called bypass. Based on the implementation, it seems that the new header that gets bypassed is:

'x-msw-intention': 'bypass'

I'm not suggesting similar support should be implemented for MSW 2.x as existed fro MSW 1.x. I just want to bring this change into your attention.

Alternatives and workarounds

As a workaround, the old header can be respected in userland:

  server.listen({
    onUnhandledRequest(request, print) {
      if (request.headers.get('x-msw-bypass') === 'true') {
        return;
      }

      print.warning();
    },
  })
);

Not sure if the new bypass utility can be used in some way that allows the implementation to not depend on implementation details.

Could not find a declaration file for module 'next-test-api-route-handler'.

The problem

Hi! The import import { testApiHandler } from "next-test-api-route-handler"; gives me the following typescript error:

Could not find a declaration file for module 'next-test-api-route-handler'. '/Users/jakejones/Documents/repos/git/next-test-api-route-handler-import/node_modules/next-test-api-route-handler/dist/esm/index.mjs' implicitly has an 'any' type.
  There are types at '/Users/jakejones/Documents/repos/git/next-test-api-route-handler-import/node_modules/next-test-api-route-handler/dist/types/src/index.d.ts', but this result could not be resolved when respecting package.json "exports". The 'next-test-api-route-handler' library may need to update its package.json or typings.ts(7016)

I think the issue is related to prs such as:

Reproduction steps

For basic reproduction: https://github.com/jakejones2/next-test-api-route-handler-import

Suggested solution

A quick fix seems to be changing package.json as follows:

"exports": {
    ".": {
      "types": "./dist/types/src/index.d.ts",
      "import": "./dist/esm/index.mjs",
      "require": "./dist/index.js",
      "default": "./dist/index.js"
    },
    "./package": "./package.json",
    "./package.json": "./package.json"
  },

However, looking at similar pull requests, the problem might require an index.d.mts file. Something like this:

"exports": {
  ".": {
    "import": {
      "types": "./dist/types/src/index.d.mts",
      "default": "./dist/esm/index.mjs",
    },
    "require": {
      "types": "./dist/types/src/index.d.ts",
      "default": "./dist/index.js",
    }
  },
  "./package": "./package.json",
  "./package.json": "./package.json"
},
Additional context

node v.20.4.0
npm v.9.7.2

App Router Examples

According to the docs NTARH got app router and edge route support in version 4..

However, I have been unable to find any examples of tests using the app router. Additionally, it seems like the types require a NextApiRequest/NextApiReponse,

Finally, if I simply ignore the types, I see API route returned a Response object in the Node.js runtime, this is not supported. Please use runtime: "edge" as an error in the response.

I am guessing this is all supported based on the docs, but don't see how. Any ideas?

Revert accidental BC

Problematic behavior

90caad6, which manually updated dependencies, accidentally bumped the Next.js peer dependency from next@10 to next@11. The culprit was npm-check-updates without the --dep option. This has since been fixed.

The coming update will address this issue along with #295 by extending NTARH compat all the way back to next@9.

Reproduction steps
Expected behavior
Additional context

Support for edge function API

It'd be great if we could get an update to the handler parameter to also support the edge function format

i.e. handler(req: NextRequest): Promise<Response> (rather than the NextApiRequest/NextApiResponse)

Thanks

Verify support for app-based route handlers

It seems like NTARH works perfectly fine with the app-based route handlers as it does with the page-based ones (no one has reported any issues), but I haven't tested it yet since Vercel is still actively working on the feature. However, it seems like things are stable enough now that I can add some tests and update the documentation to verify NTARH's compatibility.

This issue exists to remind me, along with adding a signature for edge routes.

Compat issue with Next 10.2.0

Problematic behavior

The automated compat test reports incompatibility with Next 10.2.0. Seems a parameter has been removed from the api resolving function's interface. Fix is incoming.

Reproduction steps
Expected behavior
Additional context

Able to fetch data through axios

The Issue

When I test nextjs api, the body that I send is always undefined if I don't Stringify at test level and parse at api level.
It's working, but when I don't make test, the JSON.parse() stay there and I also have to check wether the request body is stringified or not.

From the test I have to stringify my body, otherwise it is undefined on the api
client level

I want to send the request through a client such as postman or web browser I am getting this exception becuase it tries to parse a plain object instead of string.

postman level

If I want to use both at test level and client level I have to check if I can parse or not the body
api level

The solution

Access to "axios" parameter in the test callback to send body as plain object and avoid to stringify data

ReferenceError: Request is not defined

The problem

I'm encountering a ReferenceError: Request is not defined when attempting to test an API route using next-test-api-route-handler. The test is designed to verify that a GET request to /api/test should return {hello: 'world'}. However, the test fails with the mentioned error.

Here's the code snippet where the error occurs:

import { testApiHandler } from "next-test-api-route-handler";

describe("GET /api/test", () => {
  it("Returns {hello: 'world'}", async () => {
    await testApiHandler({
      appHandler: {
        GET: async () => {
          return Response.json({ hello: "world" }, { status: 200 });
        },
      },

      async test({ fetch }) {
        const res = await fetch();
        expect(res.status).toBe(200);
        const json = await res.json();
        expect(json).toStrictEqual({ hello: "world" });
      },
    });
  });
});
Reproduction steps
Additional context
  • OS: Mac 14.2.1
  • Node version: 20.10.0
  • Babel: yes, version 7.18
  • TypeScript: yes, version 5.2.2
  • Next.js: 13.5.4
  • Jest: 29.6.1

Error message in terminal:

ReferenceError: Request is not defined

  37 | describe("GET /api/test", () => {
  38 |   it("Returns {hello: 'world'}", async () => {
> 39 |     await testApiHandler({
     |                         ^
  40 |       appHandler: {
  41 |         GET: async () => {
  42 |           return Response.json({ hello: "world" }, { status: 200 });

  at Object.Request (node_modules/next/src/server/web/spec-extension/request.ts:10:34)
  at Object.<anonymous> (node_modules/next/server.js:2:16)
  at createAppRouterServer (node_modules/next-test-api-route-handler/dist/src/index.js:161:25)
  at testApiHandler (node_modules/next-test-api-route-handler/dist/src/index.js:110:57)
  at Object.<anonymous> (tests/route.test.ts:39:25)

Recursive redirection occurs when redirecting within the handler

Note:
This is not a problem caused by this library itself, but rather an issue that can arise when using the library. It is being documented as an issue with the intention of highlighting potential problems that may occur when using the library, and to request its inclusion in the documentation.

Overview of the Issue

When redirecting within an API handler, if you simply call fetch() in the test, it recursively triggers redirection. As a result, an error stating redirect count exceeded occurs.

Reproduction Test Code

  test('redirect', async () => {
    await testApiHandler({
      pagesHandler: (_, res) => res.redirect(302, '/'),
      test: async ({ fetch }) => {
        const res = await fetch({ method: 'GET' })
        expect(res.redirected).toBeTruthy()
      }
    })
  })

Executing this code results in the following error:

    TypeError: fetch failed

       8 |       pagesHandler: (_, res) => res.redirect(302, '/'),
       9 |       test: async ({ fetch }) => {
    > 10 |         const res = await fetch({ method: 'GET' })
         |                     ^
      11 |         expect(res.redirected).toBeTruthy()
      12 |       }
      13 |     })

(snip)

    Cause:
    redirect count exceeded

      at async node:internal/deps/undici/undici:10342:20
      at async node:internal/deps/undici/undici:10342:20
      at async node:internal/deps/undici/undici:10342:20
      (The above line repeats)

Solution Approach

By adding redirect: 'manual' when calling fetch(), it prevents automatic redirection to the redirect destination, allowing validation of the response.

Updated test code:

  test.skip('redirect', async () => {
    await testApiHandler({
      pagesHandler: (_, res) => res.redirect(302, '/'),
      test: async ({ fetch }) => {
        const res = await fetch({ method: 'GET', redirect: 'manual' })
        expect(res.status).toEqual(302)
        expect(res.headers.get('location')).toEqual('/')
      }
    })
  })

See also: https://developer.mozilla.org/en-US/docs/Web/API/fetch#redirect

Expected Fix

To prevent similar issues in the future, it would be beneficial to explicitly mention this in the documentation.

How to set cookie header?

I'm trying to set a cookie header so that my handler can access request.cookies, but can't figure out how to do it.

I want the equivalent of this:

const response = await supertest(app)
  .get(PATH)
  .set('Cookie', `magic-auth-token=${token}`)
  .expect(200);

I tried:

requestPatcher: request =>
  (request.headers = { 'set-cookie': [`magic-auth-token=${token}`] }),

and

requestPatcher: request =>
  (request.headers = { cookie: `magic-auth-token=${token}` }),

both of which do not work. How can I set a cookie?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.