Search code examples
reactjstypescriptnext.jsjestjsts-jest

How to test NextJS App Router API route with Jest


I have a very simple API route which I would like to test:

File ./src/app/api/name

import { NextResponse } from 'next/server';

export async function GET() {
    const name = process.env.NAME;

    return NextResponse.json({
        name,
    });
}

I have tried to test this like this:

import { GET } from './route';

describe('name', () => {
    it('should return url from environment variables', async () => {
        const result = await GET();
        const { name } = await result.json();

        expect(name).toEqual('test');
    });
});

But then an error is thrown:

 FAIL  src/app/api/name/route.spec.ts
  ● Test suite failed to run

    ReferenceError: Response is not defined

       9 | }
      10 |

      at Object.Response (node_modules/next/src/server/web/spec-extension/response.ts:29:51)
      at Object.<anonymous> (node_modules/next/dist/server/web/exports/next-response.js:12:19)
      at Object.<anonymous> (src/api/name/route.ts:11:62)
      at Object.<anonymous> (src/api/name/route.spec.ts:5:16)

I tried to follow some instructions on testing NextJS API routes, but they're all based on the Pages Router.

How can I properly test this?


Solution

  • I have found the solution. The test didn't work, since my jest configuration sets 'testEnvironment' to 'jest-environment-jsdom'.

    The initial test setup does work after adding the following to the top of the .spec.ts file:

    /**
     * @jest-environment node
     */