Bird
Raised Fist0
NextJSframework~5 mins

Testing API routes in NextJS - Cheat Sheet & Quick Revision

Choose your learning style10 modes available
Recall & Review
beginner
What is the main purpose of testing API routes in Next.js?
To ensure that the API endpoints respond correctly to requests, handle data properly, and return expected status codes and responses.
Click to reveal answer
beginner
Which testing library is commonly used to test Next.js API routes?
Jest is commonly used along with libraries like Supertest to test Next.js API routes by simulating HTTP requests.
Click to reveal answer
intermediate
How do you simulate a GET request to a Next.js API route in a test?
Use Supertest to send a GET request to the API handler and check the response status and body.
Click to reveal answer
intermediate
Why should API route tests be isolated and not depend on external services?
To make tests reliable and fast by avoiding failures caused by network issues or changes in external services.
Click to reveal answer
intermediate
What is a simple way to test a POST request with JSON data in Next.js API routes?
Use Supertest to send a POST request with a JSON body and verify the API response matches expected results.
Click to reveal answer
Which library helps simulate HTTP requests to test Next.js API routes?
AExpress
BReact Testing Library
CSupertest
DRedux
What should you check when testing an API route response?
AThe database schema
BResponse status and body
CThe UI rendering
DOnly the response headers
Why is it important to mock external services in API route tests?
ATo test the external service itself
BTo increase test complexity
CTo avoid writing tests
DTo keep tests fast and reliable
Which HTTP method is used to retrieve data from an API route?
AGET
BPOST
CPUT
DDELETE
In Next.js API route tests, what does the 'handler' represent?
AThe function that handles the API request
BThe React component
CThe database connection
DThe CSS styling
Explain how you would write a test for a Next.js API route that handles a POST request with JSON data.
Think about simulating the request and checking the response.
You got /4 concepts.
    Describe why isolating API route tests from external services is important and how you might achieve it.
    Consider what happens if the external service is down during testing.
    You got /4 concepts.

      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

      1. Step 1: Understand API route role

        API routes handle backend logic and respond to client requests in Next.js.
      2. Step 2: Purpose of testing API routes

        Testing ensures these routes respond correctly and handle inputs as expected.
      3. Final Answer:

        To verify that the backend API responds correctly to requests -> Option A
      4. 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

      1. Step 1: Identify default export usage

        Next.js API routes usually export a default function as handler.
      2. Step 2: Correct import syntax for default export

        Use import handler from 'path' to import default export correctly.
      3. Final Answer:

        import handler from '../pages/api/hello'; -> Option A
      4. 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' })?
      import handler from '../pages/api/hello';
      import { createMocks } from 'node-mocks-http';
      
      test('returns 200 status', async () => {
        const { req, res } = createMocks({ method: 'GET' });
        await handler(req, res);
        expect(res._getStatusCode()).toBe(200);
      });
      medium
      A. 404
      B. 200
      C. 500
      D. 400

      Solution

      1. Step 1: Understand handler response

        The handler sets status 200 and sends JSON with message 'OK'.
      2. Step 2: Test checks status code

        The test expects status code 200, matching the handler's response.
      3. Final Answer:

        200 -> Option B
      4. 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

      1. Step 1: Check handler invocation

        API route handlers are async functions and must be awaited in tests.
      2. 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.
      3. Final Answer:

        Missing async/await for the handler call -> Option D
      4. 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

      1. Step 1: Understand method-specific testing

        Each HTTP method requires a separate mock request to simulate different behaviors.
      2. 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.
      3. Final Answer:

        Create separate tests using createMocks with method set to 'GET' and 'POST', then call handler for each -> Option C
      4. 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 unknown strong while earning +1 Grip toward your certificate.

      10 questions~5 mineasy hard