0
0
NextJSframework~10 mins

Testing API routes in NextJS - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Testing API routes
Write API Route Handler
Write Test Case
Run Test Runner
Send Mock Request to API
API Handler Processes Request
Return Response
Test Runner Checks Response
Pass or Fail Test
End
This flow shows how writing a test sends a fake request to the API route, which processes it and returns a response that the test checks.
Execution Sample
NextJS
import handler from './api/hello';
import { createMocks } from 'node-mocks-http';

test('GET /api/hello returns 200 and message', async () => {
  const { req, res } = createMocks({ method: 'GET' });
  await handler(req, res);
  expect(res._getStatusCode()).toBe(200);
  expect(res._getData()).toBe('Hello World');
});
This test sends a fake GET request to the /api/hello route and checks if it returns status 200 and the message 'Hello World'.
Execution Table
StepActionRequest MethodAPI Handler Response StatusAPI Handler Response BodyTest Assertion
1Create mock GET request and response objectsGETN/AN/AN/A
2Call API handler with mock request and responseGET200'Hello World'N/A
3Check response status codeGET200'Hello World'Pass if status is 200
4Check response body contentGET200'Hello World'Pass if body is 'Hello World'
5Test endsN/AN/AN/ATest passes if all assertions pass
💡 Test ends after all assertions pass or fail
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
req.methodundefinedGETGETGETGET
res.statusCodeundefinedundefined200200200
res.bodyundefinedundefined'Hello World''Hello World''Hello World'
Key Moments - 3 Insights
Why do we use mock request and response objects instead of real HTTP calls?
Using mock objects lets tests run fast and isolated without needing a real server or network, as shown in Step 1 of the execution_table.
How does the test know if the API route works correctly?
The test checks the response status and body after the handler runs (Steps 3 and 4), confirming the API behaves as expected.
What happens if the API handler returns a different status or message?
The test assertions in Steps 3 and 4 will fail, causing the test to fail and alerting you to the problem.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the response status code after Step 2?
A500
B404
C200
Dundefined
💡 Hint
Check the 'API Handler Response Status' column at Step 2 in the execution_table.
At which step does the test check the response body content?
AStep 4
BStep 2
CStep 1
DStep 5
💡 Hint
Look at the 'Test Assertion' column in the execution_table for when the body is checked.
If the mock request method was changed to POST, what would likely happen in the test?
AThe test would still pass without changes
BThe API handler might return a different status, causing test failure
CThe response body would be 'Hello World' anyway
DThe test runner would crash
💡 Hint
Consider how the API handler processes different methods and how assertions depend on expected responses.
Concept Snapshot
Testing API routes in Next.js:
- Use mock request and response objects to simulate HTTP calls.
- Call the API handler function directly with mocks.
- Check response status and body with assertions.
- Tests run fast without a real server.
- Use libraries like node-mocks-http for mocks.
Full Transcript
Testing API routes in Next.js involves writing test cases that simulate HTTP requests using mock request and response objects. The test calls the API route handler function directly with these mocks. The handler processes the request and sets the response status and body. The test then checks these response values with assertions to confirm the API behaves as expected. This approach avoids real network calls, making tests fast and reliable. Common tools include node-mocks-http to create mock objects. The test flow starts by creating mocks, calling the handler, then checking the response, and finally passing or failing the test based on assertions.