Bird
Raised Fist0
NextJSframework~20 mins

Testing server components in NextJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Server Component Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the rendered output of this Next.js server component?
Consider this server component in Next.js 14+ that fetches data and renders it. What will be the output when rendered?
NextJS
import React from 'react';

async function getData() {
  return { message: 'Hello from server!' };
}

export default async function Greeting() {
  const data = await getData();
  return <h1>{data.message}</h1>;
}
AError: Cannot use await in server component
B<h1>undefined</h1>
C<h1>Hello from client!</h1>
D<h1>Hello from server!</h1>
Attempts:
2 left
💡 Hint
Server components can use async/await to fetch data before rendering.
❓ lifecycle
intermediate
1:30remaining
When does a Next.js server component run its code?
In Next.js 14+, when does the code inside a server component execute?
AOnly on the server during the initial page load and on server-side navigation
BOnly on the client after hydration
COn both client and server simultaneously
DOnly when a user clicks a button inside the component
Attempts:
2 left
💡 Hint
Server components run where the server renders the page.
🔧 Debug
advanced
2:30remaining
Why does this server component cause a hydration mismatch?
Examine this server component code. Why does it cause a hydration mismatch error in Next.js?
NextJS
import React from 'react';

export default function Time() {
  const now = new Date().toISOString();
  return <p>{now}</p>;
}
ABecause the component uses Date inside a server component, causing different output on server and client
BBecause server components cannot return JSX elements
CBecause the component uses React hooks incorrectly
DBecause the component is missing async keyword
Attempts:
2 left
💡 Hint
Server components render once on the server, but client hydration expects stable output.
📝 Syntax
advanced
3:00remaining
Which option correctly defines a server component with a server action in Next.js 14+?
Select the correct syntax for a server component that includes a server action to handle a form submission.
A
export default function Form() {
  function submit(data) {
    console.log(data);
  }
  return &lt;form onSubmit={submit}&gt;&lt;button type="submit"&gt;Send&lt;/button&gt;&lt;/form&gt;;
}
B
export default async function Form() {
  async function submit(data) {
    'use server';
    console.log(data);
  }
  return &lt;form action={submit}&gt;&lt;button type="submit"&gt;Send&lt;/button&gt;&lt;/form&gt;;
}
C
export default async function Form() {
  function submit(data) {
    'use server';
    console.log(data);
  }
  return &lt;form action={submit}&gt;&lt;button type="submit"&gt;Send&lt;/button&gt;&lt;/form&gt;;
}
D
export default function Form() {
  async function submit(data) {
    console.log(data);
  }
  return &lt;form action={submit}&gt;&lt;button type="submit"&gt;Send&lt;/button&gt;&lt;/form&gt;;
}
Attempts:
2 left
💡 Hint
Server actions require the 'use server' directive inside the function and must be async.
❓ state_output
expert
3:00remaining
What is the value of count after rendering this mixed server/client component setup?
Given this Next.js 14+ setup with a server component rendering a client component, what is the final count value displayed after clicking the button twice?
NextJS
import React, { useState } from 'react';

// Client component
'use client';
export function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;
}

// Server component
export default function Page() {
  return <Counter />;
}
ACount: 1
BCount: 0
CCount: 2
DCount: undefined
Attempts:
2 left
💡 Hint
Client components manage state and update on user interaction.

Practice

(1/5)
1. What is the main reason to write tests for Next.js server components?
easy
A. To catch errors early and keep the app stable
B. To improve client-side rendering speed
C. To reduce the size of the JavaScript bundle sent to the browser
D. To enable hot module replacement during development

Solution

  1. Step 1: Understand the purpose of testing server components

    Testing server components helps find bugs before the app runs in production, ensuring stability.
  2. Step 2: Compare options with testing goals

    Only catching errors early and keeping the app stable matches the main goal of testing server components.
  3. Final Answer:

    To catch errors early and keep the app stable -> Option A
  4. Quick Check:

    Testing purpose = catch errors early [OK]
Hint: Testing server components mainly prevents bugs early [OK]
Common Mistakes:
  • Confusing testing with client-side performance optimization
  • Thinking tests reduce bundle size
  • Mixing testing with development tooling features
2. Which of the following is the correct way to import the render function for testing a Next.js server component using @testing-library/react?
easy
A. import { renderComponent } from '@testing-library/react';
B. import render from '@testing-library/react';
C. import { renderServer } from '@testing-library/react';
D. import { render } from '@testing-library/react';

Solution

  1. Step 1: Recall the correct import syntax

    The official way to import render is using named import: { render } from '@testing-library/react'.
  2. Step 2: Check other options for correctness

    Options A, B, and D use incorrect import names or default import which is not supported.
  3. Final Answer:

    import { render } from '@testing-library/react'; -> Option D
  4. Quick Check:

    Correct import = named render [OK]
Hint: Use named import { render } from testing-library [OK]
Common Mistakes:
  • Using default import instead of named import
  • Using wrong function names like renderComponent
  • Assuming renderServer exists in the library
3. Given this server component test code, what will be the output of the test?
import { render } from '@testing-library/react';
import Greeting from './Greeting';

test('renders greeting message', () => {
  const { getByText } = render();
  getByText('Hello, Alice!');
});

Assuming Greeting renders Hello, {name}! correctly.
medium
A. Test fails because the component does not render
B. Test fails because getByText is not a function
C. Test passes because the text 'Hello, Alice!' is found
D. Test passes but does not check the text content

Solution

  1. Step 1: Understand what getByText does

    getByText searches the rendered output for the exact text. If found, it returns the element; otherwise, it throws an error.
  2. Step 2: Analyze the test code behavior

    The test renders Greeting with name 'Alice', so it should render 'Hello, Alice!'. getByText('Hello, Alice!') will find this text, so no error is thrown and test passes.
  3. Final Answer:

    Test passes because the text 'Hello, Alice!' is found -> Option C
  4. Quick Check:

    getByText finds text = test passes [OK]
Hint: getByText throws error if text missing, else test passes [OK]
Common Mistakes:
  • Assuming getByText returns null instead of throwing error
  • Thinking render does not work on server components
  • Ignoring that test fails if text not found
4. You wrote this test for a server component but it fails with "TypeError: Cannot read property 'props' of undefined". What is the likely cause?
import { render } from '@testing-library/react';
import UserProfile from './UserProfile';

test('renders user name', () => {
  const { getByText } = render(UserProfile({ name: 'Bob' }));
  getByText('User: Bob');
});
medium
A. You forgot to import React in the test file
B. You called the component as a function instead of as JSX
C. You used getByText incorrectly without await
D. You passed props with wrong property name

Solution

  1. Step 1: Identify how the component is rendered

    The test calls UserProfile({ name: 'Bob' }) directly as a function instead of using JSX syntax <UserProfile name="Bob" /> inside render.
  2. Step 2: Understand why this causes error

    Server components expect JSX usage for rendering. Calling as function returns undefined or unexpected value, causing TypeError when render tries to access props.
  3. Final Answer:

    You called the component as a function instead of as JSX -> Option B
  4. Quick Check:

    Render needs JSX, not direct function call [OK]
Hint: Always render components as JSX, not function calls [OK]
Common Mistakes:
  • Calling component as a plain function
  • Forgetting JSX angle brackets in render
  • Misunderstanding getByText usage
5. You want to test a server component that fetches data asynchronously before rendering. Which approach correctly tests the component's rendered output after data is loaded?
async function fetchUser() { return { name: 'Eve' }; }

function User() {
  const user = fetchUser();
  return <div>User: {user.name}</div>;
}

How should you write the test?
hard
A. Call fetchUser inside the test and pass data as prop to User component
B. Mock fetchUser to return data synchronously and render User component normally
C. Use async/await in the test and render User component with suspense fallback
D. Render User component directly without mocking or waiting

Solution

  1. Step 1: Understand server component data fetching

    Server components can fetch data asynchronously but tests must control data to avoid real async calls.
  2. Step 2: Choose testing approach

    Calling fetchUser in test and passing data as prop lets test run synchronously and check output reliably.
  3. Step 3: Evaluate other options

    Mocking fetchUser synchronously inside component is complex; suspense fallback is for client components; rendering without waiting causes errors.
  4. Final Answer:

    Call fetchUser inside the test and pass data as prop to User component -> Option A
  5. Quick Check:

    Pass data as prop after fetching in test [OK]
Hint: Fetch data in test, pass as prop to component [OK]
Common Mistakes:
  • Trying to test async fetch inside component directly
  • Ignoring need to mock or control data in tests
  • Using suspense fallback incorrectly in server component tests
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