TestingNext.jsSoftware EngineeringDeveloper ToolingWeb Development

Unit Test Next.js API Routes with TypeScript.

Unit testing Next.js API routes in TypeScript with Jest: GET and POST handlers, error cases, and the other scenarios worth covering. A personal reference.

Ink-and-wash illustration of a workbench from above: screwdrivers, a wrench, and other tools around sheets of hand-drawn technical sketches.
Table of Contents (5)

Testing API routes sucks, especially in TypeScript. This covers unit testing Next.js API routes with TypeScript using Jest and React Testing Library.

Why Test API Routes?

Tests confirm that your routes work as expected: they return the correct data, handle errors properly, and respond to different request types (GET, POST, PUT, DELETE).

They also catch bugs, security issues, and performance problems early, before they become bigger problems.

And they document each route's behavior, which makes the code more maintainable and easier for other developers to understand.

Tools and Libraries

We'll use these tools and libraries:

  • Jest: a JavaScript testing framework that provides a complete testing solution for JavaScript applications.

  • React Testing Library: a library for testing React components that provides a set of helper functions to interact with the DOM.

  • node-mocks-http: a library that provides mock objects for Node.js HTTP requests and responses.

  • dotenv: a library that loads environment variables from a .env file into process.env.

  • @types/node: a package that provides TypeScript definitions for Node.js built-in modules.

Install them with:

npm install --save-dev jest @testing-library/react node-mocks-http dotenv @types/node[^3^][3]

Then configure Jest to work with Next.js and TypeScript by creating a jest.config.js file in the root of your project:

module.exports = {
  testEnvironment: 'jsdom',
  transform: {
    '^.+\\.(js|jsx|ts|tsx)$': '<rootDir>/node_modules/babel-jest',
  },
  moduleNameMapper: {
    '^.+\\.(css|less|scss)$': 'identity-obj-proxy',
  },
}

This configuration tells Jest to use jsdom as the test environment, use Babel to transform JavaScript and TypeScript files, and mock CSS modules with an identity object proxy.

Testing GET Requests

To test GET requests to a Next.js API route using the App Router, you need a mock request object, a mock response object, and a handler function representing your route. node-mocks-http creates the mock objects, and you pass them to the handler.

Here's an example that tests a GET request to an API route that returns a list of users:

// app/api/users.page.ts
import type { NextRequest } from 'next/server'
import type { NextResponse } from 'next/server'

type User = {
  id: number
  name: string
}

const users: User[] = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
]

export default function handler(req: NextRequest) {
  return NextResponse.json(users)
}

// app/api/users.test.ts
import { createMocks } from 'node-mocks-http'
import handler from './users.page'

describe('/api/users', () => {
  test('returns a list of users', async () => {
    const { req, res } = createMocks({
      method: 'GET',
    })

    const response = await handler(req)

    expect(response.status).toBe(200)
    expect(await response.json()).toEqual([
      { id: 1, name: 'Alice' },
      { id: 2, name: 'Bob' },
    ])
  })
})

Here, createMocks from node-mocks-http creates a mock request object with the method property set to 'GET' and a mock response object. We pass the request to our handler function and wait for the response.

Then Jest’s expect function and its matchers (e.g., toBe, toEqual) assert the expected behavior: a 200 status code and a list of users.

Testing POST Requests

To test POST requests to a Next.js API route using the App Router, create a mock request object with the method property set to 'POST' and the body property set to the data you want to send, plus a handler function that represents your route.

Here's an example that tests a POST request to an API route that creates a new user:

// app/api/users.page.ts
import type { NextRequest } from 'next/server'
import type { NextResponse } from 'next/server'

type User = {
  id: number
  name: string
}

let users: User[] = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
]

export default function handler(req: NextRequest) {
  if (req.method === 'POST') {
    const newUser = req.body as User
    newUser.id = users.length + 1
    users.push(newUser)
    return NextResponse.created(users)
  } else {
    return NextResponse.json(users)
  }
}

// app/api/users.test.ts
import { createMocks } from 'node-mocks-http'
import handler from './users.page'

describe('/api/users', () => {
  test('creates a new user', async () => {
    const { req, res } = createMocks({
      method: 'POST',
      body: { name: 'Charlie' },
    })

    const response = await handler(req)

    expect(response.status).toBe(201)
    expect(await response.json()).toEqual([
      { id: 1, name: 'Alice' },
      { id: 2, name: 'Bob' },
      { id: 3, name: 'Charlie' },
    ])
  })
})

Here, createMocks creates a mock request object with the method property set to 'POST' and the body property set to an object with the name property set to 'Charlie'. We pass the request to our handler function and wait for the response.

The assertions expect a 201 status code and a list of users, including the new user.

Testing Other Scenarios

You can also test other scenarios and inputs with the App Router, such as error handling, validation, authentication, authorization, headers, cookies, query parameters, and body parameters.

Here's an example that tests error handling in an API route that returns a user by ID:

// app/api/users/[id].page.ts
import type { NextRequest } from 'next/server'
import type { NextResponse } from 'next/server'

type User = {
  id: number
  name: string
}

const users: User[] = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
]

export default function handler(req: NextRequest) {
  const id = Number(req.query.id)
  const user = users.find((user) => user.id === id)
  if (user) {
    return NextResponse.json(user)
  } else {
    return NextResponse.notFound({ message: 'User not found' })
  }
}

// app/api/users/[id].test.ts
import { createMocks } from 'node-mocks-http'
import handler from './[id].page'

describe('/api/users/[id]', () => {
  test('returns a user by ID', async () => {
    const { req, res } = createMocks({
      method: 'GET',
      query: { id: '1' },
    })
    const response = await handler(req)
    expect(response.status).toBe(200)
    expect(await response.json()).toEqual({ id: 1, name: 'Alice' })
  })

  test('returns an error if the user is not found', async () => {
    const { req, res } = createMocks({
      method: 'GET',
      query: { id: '3' },
    })
    const response = await handler(req)
    expect(response.status).toBe(404)
    expect(await response.json()).toEqual({ message: 'User not found' })
  })
})

Here, createMocks creates two sets of mock objects for our tests. The first has a mock request object with the method property set to 'GET' and the query property set to an object with the id property set to '1'. The second is the same except the id property is '3'. We pass each request and its mock response object to our handler function and wait for it to finish.

In the first test, we expect a 200 status code and a user object with the id property set to 1. In the second, we expect a 404 status code and an error message.