0
0
NextJSframework~10 mins

Testing API routes in NextJS - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the testing library for Next.js API routes.

NextJS
import { [1] } from 'next-test-api-route-handler';
Drag options to blanks, or click blank then click option'
AtestApiHandler
BuseRouter
Crender
DgetServerSideProps
Attempts:
3 left
💡 Hint
Common Mistakes
Using render which is for React components, not API routes.
Using useRouter which is for client-side routing.
Using getServerSideProps which is for server-side rendering.
2fill in blank
medium

Complete the code to define a test that checks the API route returns status 200.

NextJS
test('returns status 200', async () => {
  await testApiHandler({
    handler: apiRoute,
    test: async ({ fetch }) => {
      const res = await fetch();
      expect(res.status).toBe([1]);
    },
  });
});
Drag options to blanks, or click blank then click option'
A404
B200
C500
D302
Attempts:
3 left
💡 Hint
Common Mistakes
Using 404 which means the route was not found.
Using 500 which means server error.
Using 302 which means redirect.
3fill in blank
hard

Fix the error in the test by completing the code to import the API route correctly.

NextJS
import [1] from '../../pages/api/hello';
Drag options to blanks, or click blank then click option'
AapiRoute
Bhandler
CapiHandler
DhelloApi
Attempts:
3 left
💡 Hint
Common Mistakes
Using a name that does not match the default export.
Using a named import instead of default import.
4fill in blank
hard

Fill both blanks to test the API route returns JSON with a message property.

NextJS
test('returns JSON with message', async () => {
  await testApiHandler({
    handler: apiRoute,
    test: async ({ fetch }) => {
      const res = await fetch();
      const data = await res.[1]();
      expect(data).toHaveProperty([2]);
    },
  });
});
Drag options to blanks, or click blank then click option'
Ajson
B'message'
C'status'
Dtext
Attempts:
3 left
💡 Hint
Common Mistakes
Using res.text() instead of res.json().
Checking for a wrong property like 'status'.
5fill in blank
hard

Fill all three blanks to test the API route handles POST requests with JSON body.

NextJS
test('handles POST request', async () => {
  await testApiHandler({
    handler: apiRoute,
    test: async ({ fetch }) => {
      const res = await fetch('', {
        method: [1],
        headers: { 'Content-Type': [2] },
        body: JSON.stringify({ name: 'Next.js' }),
      });
      const data = await res.json();
      expect(data).toHaveProperty([3]);
    },
  });
});
Drag options to blanks, or click blank then click option'
A'POST'
B'application/json'
C'name'
D'GET'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'GET' method instead of 'POST'.
Missing or wrong Content-Type header.
Checking for wrong property in response.