TestingNext.jsWeb DevelopmentSoftware EngineeringDeveloper Tooling

Testing Routes in Next.js 13

Note: 8/28— I’ve refreshed the content after some experimentation and the release of 13.5.

Table of Contents (15)

Update, 8/28: I’ve refreshed the content after some experimentation and the release of 13.5.

  • Built a gist that contains examples.

  • Leans less on node-mocks.

  • Explains routing (because it feels weird without it).

Complete examples are in the associated Gist: https://gist.github.com/zachshallbetter.

This guide covers several ways to test routes in Next.js 13, with the tools you need to confirm that routes behave correctly.

What is routing?

Routing is how a web application decides how to respond to a request for a specific URL or URI (Uniform Resource Identifier). It defines rules or patterns that map those URLs to specific actions or content in the application. It serves several purposes:

  • Navigation: Users move between pages or views. Clicking a link or typing a URL in the address bar loads the corresponding page.

  • Content delivery: The right content or data is delivered for a given URL. That can mean rendering HTML templates, serving JSON, or performing other actions based on the URL.

  • State management: Different URLs can represent different states or views of the application, and routing helps maintain and switch between them.

  • Authentication and authorization: Routing can protect certain routes or pages so that only authenticated and authorized users can reach them. It’s a critical part of web application security.

  • SEO (Search Engine Optimization): Search engines use the URL structure of a website to index its content, so well-structured, semantic URLs can improve search ranking.

In modern web development, frameworks and libraries handle routing, which makes routes easier to define and manage. Next.js, React Router, Angular Router, and Vue Router all provide tools and APIs for it.

Testing confirms that your routes work as expected and handle different scenarios. Your mileage may vary with the type of route and the level of testing you want.

Testing tools

Jest and node-mocks-http are two tools for testing routes and server-side logic, particularly in Next.js applications. Here’s what each does.

Jest

Jest is a JavaScript testing framework developed by Facebook. It’s used for both client-side and server-side code, and it’s known for simplicity, speed, and a strong feature set. Its main features:

  • Test runner: Executes test suites and individual test cases.

  • Assertion library: Includes functions like expect for making assertions and checking expected outcomes.

  • Mocking: Built-in mocking for functions, modules, and timers makes it easy to isolate and control parts of your code.

  • Asynchronous testing: Supports async/await and the done callback.

  • Snapshot testing: Creates and compares snapshots of rendered components, which is useful for UI components.

  • Parallel test execution: Runs tests in parallel for better performance.

  • Code coverage: Generates coverage reports to identify untested code.

For testing routes in Next.js, Jest is the framework that runs the test cases. Its expect and other assertion functions check the behavior of routes and their components. It’s particularly useful for asynchronous operations, such as data fetching with getServerSideProps and getStaticProps.

node-mocks-http

node-mocks-http is a Node.js library that provides mock objects for simulating HTTP requests and responses. It’s especially valuable for testing server-side logic in Node.js applications, including Express.js and, in our case, Next.js. Its main features:

  • Customization: You can customize the properties and methods of the mock objects to simulate various scenarios and test edge cases.

  • Middleware testing: It suits testing middleware functions that process HTTP requests and responses.

  • Integration with testing frameworks: It works with frameworks like Jest to test server-side code.

When testing routes in Next.js, developers use it to create mock request and response objects. They pass those objects to route functions to simulate HTTP requests and observe the responses. Customizing the mocks lets them simulate different scenarios, test error handling, and validate route behavior.

Testing with Jest and node-mocks-http

Jest, combined with node-mocks-http, is a flexible way to test route behavior. With this approach, you can:

  • Create mock functions that capture calls, arguments, return values, and contexts.

  • Mock modules and their exports, including ES and CommonJS modules.

  • Mock constructors and instances of classes.

  • Configure mock implementations and return values for different scenarios.

  • Restore the original behavior of mocked functions and modules.

How to test routes

There are two primary approaches.

  • Development server and browser: Run npm run dev in your terminal and navigate to the route’s URL. You can visually inspect how the route renders and check the console for errors or warnings.

  • Testing frameworks and libraries: Automate route testing for repeatability with unit or integration tests that don’t need a browser. We’ll focus on this approach.

Testing a route means creating a controlled environment to send requests to the route and verify the responses. Here’s how it typically works.

Set up the testing environment

  • Import the testing libraries. In a Next.js application, you’ll commonly use a framework like Jest and a library like node-mocks-http for creating mock HTTP request and response objects.

  • Import the route you want to test. It should be part of your application’s codebase.

Create mock request and response objects

  • Create them with node-mocks-http or a similar tool. They mimic actual HTTP requests and responses in a controlled, predictable way.

  • Customize them to simulate various scenarios. For example, you can set the HTTP method and provide request parameters, headers, and more, depending on the route’s requirements.

Invoke the route function

  • Call the route function you imported, passing in the mock request and response objects. This simulates the route being invoked by an actual HTTP request.

Make assertions

  • After invoking the route, use the assertions your testing framework provides (e.g., Jest) to check the route’s behavior and response.

  • You can check things like:

    • The HTTP status code returned by the route (e.g., a 200 OK status for a successful request).

    • The content of the response, such as JSON data or HTML markup.

    • The presence of specific headers in the response.

    • The behavior of the route in different scenarios (e.g., error handling).

Run and review the results

  • Execute your test suite with your chosen framework (e.g., npm test for Jest).

  • The framework reports which tests passed and which failed.

Clean up (optional)

  • Depending on your framework and setup, you might need cleanup after each test case, such as resetting state or clearing temporary data.

Iterate for different scenarios

  • If tests fail, read the failure messages to understand what went wrong, then debug and adjust your route or test cases.

  • Write multiple test cases to cover various scenarios, such as success, error handling, authentication, and edge cases.

A practical example

This example sets up a test, creates mock request and response objects, and asserts the expected behavior of a route.

// Import the route file and the library
import hello from './api/hello'
import { createMocks } from 'node-mocks-http'

// Write a test using Jest
test('should return a greeting message', async () => {
  // Create mock request and response objects
  const { req, res } = createMocks({
    method: 'GET',
  })

  // Call the route function with the mock objects
  await hello(req, res)

  // Assert the expected behavior
  expect(res._getStatusCode()).toBe(200)
  expect(res._getData()).toEqual({ message: 'Hello Next.js' })
})

Alternatives

Jest and node-mocks-http aren’t the only options. Alternatives include Sinon.js, Rewire, and Proxyquire, each with its own strengths and considerations. Choose the one that suits your needs and preferences.

The associated Gist has complete code examples for testing routes with Jest and node-mocks-http.