0
0
NextjsHow-ToBeginner · 4 min read

How to Test API Route in Next.js: Simple Guide

To test an API route in Next.js, use a testing framework like Jest along with Next.js utilities to simulate HTTP requests by calling the API handler function with mock req and res objects. This lets you check the response status and data without running a server.
📐

Syntax

Testing a Next.js API route involves calling the exported handler function with mock req (request) and res (response) objects. You simulate HTTP methods and check the response.

  • handler(req, res): The API route function you want to test.
  • req: Mock request object with method, body, query, etc.
  • res: Mock response object with methods like status(), json() to capture output.
javascript
import handler from './path/to/api/route'

const req = { method: 'GET' };
const res = {
  status: jest.fn().mockReturnThis(),
  json: jest.fn()
};

await handler(req, res);
expect(res.status).toHaveBeenCalledWith(200);
expect(res.json).toHaveBeenCalledWith(expect.any(Object));
💻

Example

This example shows how to test a simple Next.js API route that returns a JSON message. It uses Jest to mock the request and response and checks the status and JSON output.

javascript
import handler from '../../pages/api/hello';

test('GET /api/hello returns 200 and message', async () => {
  const req = { method: 'GET' };
  const res = {
    status: jest.fn().mockReturnThis(),
    json: jest.fn()
  };

  await handler(req, res);

  expect(res.status).toHaveBeenCalledWith(200);
  expect(res.json).toHaveBeenCalledWith({ message: 'Hello from Next.js!' });
});
Output
PASS ./api.test.js ✓ GET /api/hello returns 200 and message (5 ms)
⚠️

Common Pitfalls

  • Not mocking res.status to return res itself causes errors because chaining like res.status(200).json(...) fails.
  • Forgetting to await the handler if it returns a promise can cause tests to pass incorrectly.
  • Not setting the method on req leads to unexpected behavior if your API route checks it.
javascript
/* Wrong way: res.status does not return res, so chaining fails */
const resWrong = {
  status: jest.fn(),
  json: jest.fn()
};

/* Right way: mockReturnThis allows chaining */
const resRight = {
  status: jest.fn().mockReturnThis(),
  json: jest.fn()
};
📊

Quick Reference

StepDescription
Import API handlerImport the function exported by your API route file.
Mock req objectCreate an object with HTTP method and any needed data.
Mock res objectMock status and json methods; status should return res for chaining.
Call handlerInvoke handler(req, res) and await if async.
Assert responseCheck that status and json were called with expected values.

Key Takeaways

Test Next.js API routes by calling the handler with mocked req and res objects.
Always mock res.status to return res for method chaining.
Await the handler if it returns a promise to ensure proper test timing.
Set the HTTP method on req to match your API route logic.
Use Jest or similar frameworks to write clear, isolated tests for API routes.