Testing API routes helps make sure your backend code works correctly. It catches mistakes early so your app runs smoothly.
0
0
Testing API routes in NextJS
Introduction
When you want to check if your API returns the right data.
When you add new features to your API and want to avoid breaking old ones.
When you fix bugs and want to confirm the problem is solved.
When you want to automate checks so you don't test manually every time.
When you want to share your API with others and ensure it behaves as expected.
Syntax
NextJS
import { createMocks } from 'node-mocks-http'; import handler from './path/to/api/route'; const { req, res } = createMocks({ method: 'GET', query: { id: '123' }, }); await handler(req, res); expect(res._getStatusCode()).toBe(200); expect(res._getJSONData()).toEqual(expect.objectContaining({ id: '123' }));
Use node-mocks-http to create fake request and response objects.
Call your API route handler with these mocks to simulate a request.
Examples
Test a POST request sending a JSON body to create a user.
NextJS
import { createMocks } from 'node-mocks-http'; import handler from './api/user'; const { req, res } = createMocks({ method: 'POST', body: { name: 'Alice' } }); await handler(req, res); expect(res._getStatusCode()).toBe(201);
Test a GET request with query parameters to fetch user data.
NextJS
import { createMocks } from 'node-mocks-http'; import handler from './api/user'; const { req, res } = createMocks({ method: 'GET', query: { id: '42' } }); await handler(req, res); expect(res._getStatusCode()).toBe(200); expect(res._getJSONData()).toContain('Alice');
Sample Program
This code defines a simple API route that returns user data for id '1'. The test simulates a GET request with id '1' and prints the status code and response data.
NextJS
import { createMocks } from 'node-mocks-http'; // Simple API route handler example export default async function handler(req, res) { if (req.method === 'GET') { const { id } = req.query; if (id === '1') { res.status(200).json({ id: '1', name: 'John Doe' }); } else { res.status(404).json({ error: 'User not found' }); } } else { res.status(405).json({ error: 'Method not allowed' }); } } // Test for the API route async function testApiRoute() { const { req, res } = createMocks({ method: 'GET', query: { id: '1' } }); await handler(req, res); console.log(res._getStatusCode()); console.log(res._getJSONData()); } testApiRoute();
OutputSuccess
Important Notes
Always test different HTTP methods your API supports.
Check both success and error responses to cover all cases.
Use descriptive test names to understand what each test checks.
Summary
Testing API routes ensures your backend works as expected.
Use mock requests and responses to simulate API calls.
Test various methods and inputs for full coverage.