Skip to content

Instantly share code, notes, and snippets.

@zachshallbetter
Created September 29, 2023 22:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zachshallbetter/3301419b75958218d1b5853147a16263 to your computer and use it in GitHub Desktop.
Save zachshallbetter/3301419b75958218d1b5853147a16263 to your computer and use it in GitHub Desktop.
Next.js Route Testing

Testing Routes in Next.js with Jest and node-mocks-http

This Gist provides a code example for testing routes in a Next.js application using the Jest testing framework and the node-mocks-http library. Testing your routes is crucial to ensure they work as expected and handle various scenarios gracefully.

Prerequisites

Before you start testing routes, make sure you have the following dependencies installed:

You can install these dependencies using npm:

npm install --save-dev jest node-mocks-http
// 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' })
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment