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 exampleexportdefaultasyncfunction 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 routeasyncfunction 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.
Practice
(1/5)
1. What is the main purpose of testing API routes in a Next.js application?
easy
A. To verify that the backend API responds correctly to requests
B. To style the API responses with CSS
C. To improve the frontend UI components
D. To deploy the API to production servers
Solution
Step 1: Understand API route role
API routes handle backend logic and respond to client requests in Next.js.
Step 2: Purpose of testing API routes
Testing ensures these routes respond correctly and handle inputs as expected.
Final Answer:
To verify that the backend API responds correctly to requests -> Option A
Quick Check:
API route testing = verify backend response [OK]
Hint: API route tests check backend responses, not frontend styles [OK]
Common Mistakes:
Confusing API testing with frontend UI testing
Thinking testing deploys the API
Assuming API testing styles responses
2. Which of the following is the correct way to import the Next.js API route handler for testing with Jest?
easy
A. import handler from '../pages/api/hello';
B. require('../pages/api/hello');
C. import { handler } from '../pages/api/hello';
D. import * as handler from '../pages/api/hello';
Solution
Step 1: Identify default export usage
Next.js API routes usually export a default function as handler.
Step 2: Correct import syntax for default export
Use import handler from 'path' to import default export correctly.
Final Answer:
import handler from '../pages/api/hello'; -> Option A
Quick Check:
Default export import = import handler from [OK]
Hint: Use default import syntax for API route handlers [OK]
Common Mistakes:
Using require() in ES module context
Trying to destructure default export
Importing all as an object unnecessarily
3. Given this test snippet for a Next.js API route handler, what will be the response status code if the handler returns res.status(200).json({ message: 'OK' })?
The handler sets status 200 and sends JSON with message 'OK'.
Step 2: Test checks status code
The test expects status code 200, matching the handler's response.
Final Answer:
200 -> Option B
Quick Check:
Handler returns 200 status code [OK]
Hint: Match expected status with handler's res.status call [OK]
Common Mistakes:
Assuming default status is 404
Confusing JSON response with status code
Not awaiting async handler
4. Identify the error in this test code for a Next.js API route:
import handler from '../pages/api/hello';
import { createMocks } from 'node-mocks-http';
test('returns 200 status', () => {
const { req, res } = createMocks({ method: 'GET' });
handler(req, res);
expect(res._getStatusCode()).toBe(200);
});
medium
A. Using _getStatusCode instead of statusCode property
B. Incorrect import path for handler
C. Wrong method used in createMocks
D. Missing async/await for the handler call
Solution
Step 1: Check handler invocation
API route handlers are async functions and must be awaited in tests.
Step 2: Identify missing async/await
The test function is not async and does not await handler, causing test to run before response is set.
Final Answer:
Missing async/await for the handler call -> Option D
Quick Check:
Async handler needs await in test [OK]
Hint: Always await async API handlers in tests [OK]
Common Mistakes:
Forgetting async keyword on test function
Not awaiting the handler call
Assuming synchronous execution
5. You want to test a Next.js API route that handles both GET and POST methods differently. Which approach correctly tests both methods in one test file?
hard
A. Use a single createMocks call with method 'GET,POST' to test both
B. Call handler once with method 'GET' and reuse the same response object for 'POST'
C. Create separate tests using createMocks with method set to 'GET' and 'POST', then call handler for each
D. Test only the GET method since POST is similar
Solution
Step 1: Understand method-specific testing
Each HTTP method requires a separate mock request to simulate different behaviors.
Step 2: Use separate mocks for GET and POST
CreateMocks should be called twice with method set to 'GET' and 'POST' respectively, calling handler each time.
Final Answer:
Create separate tests using createMocks with method set to 'GET' and 'POST', then call handler for each -> Option C
Quick Check:
Separate mocks per method = correct testing [OK]
Hint: Test each HTTP method separately with fresh mocks [OK]
Common Mistakes:
Reusing response object across methods
Testing only one method and ignoring others
Trying to combine methods in one mock
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.