Bird
Raised Fist0
NextJSframework~20 mins

React Testing Library integration in NextJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
React Testing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
1:30remaining
What does this test check for?
Given this React component and test, what behavior does the test verify?
NextJS
import { render, screen } from '@testing-library/react';
import Button from './Button';

test('renders button with correct label', () => {
  render(<Button label="Click me" />);
  const buttonElement = screen.getByRole('button');
  expect(buttonElement).toHaveTextContent('Click me');
});
AThe test checks if the button has a specific CSS class.
BThe test checks if the button is disabled by default.
CThe test checks if clicking the button triggers an alert.
DThe test checks if the button renders with the label 'Click me'.
Attempts:
2 left
💡 Hint
Look at what the expect statement is verifying.
❓ state_output
intermediate
1:30remaining
What is the output of this test after clicking?
Consider this component and test. What will the test output be after simulating a click?
NextJS
import { render, screen, fireEvent } from '@testing-library/react';
import { useState } from 'react';

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

test('increments count on click', () => {
  render(<Counter />);
  const button = screen.getByRole('button');
  fireEvent.click(button);
  expect(button).toHaveTextContent('Count: 1');
});
AThe test fails because the button text remains 'Count: 0' after click.
BThe test passes because the button text updates to 'Count: 1' after click.
CThe test throws an error because fireEvent.click is not defined.
DThe test fails because the button is disabled and cannot be clicked.
Attempts:
2 left
💡 Hint
Check how the state changes on click and what the test expects.
📝 Syntax
advanced
2:00remaining
Which test code snippet correctly waits for async content?
You want to test a component that fetches data and shows it after loading. Which test snippet correctly waits for the data to appear?
Aawait screen.findByText('Data loaded');
Bscreen.getByText('Data loaded');
Cawait screen.queryByText('Data loaded');
Dscreen.findByText('Data loaded');
Attempts:
2 left
💡 Hint
Remember which query returns a promise and waits for the element.
🔧 Debug
advanced
2:00remaining
Why does this test fail with 'Unable to find role' error?
This test fails with an error saying it cannot find a button role. What is the cause?
NextJS
import { render, screen } from '@testing-library/react';

test('finds submit button', () => {
  render(<button type="submit">Send</button>);
  const btn = screen.getByRole('button', { name: 'Submit' });
  expect(btn).toBeInTheDocument();
});
AThe button's visible text is 'Send', but the test looks for name 'Submit'.
BThe button element is not rendered because render is missing a wrapper.
CgetByRole cannot find buttons with type 'submit'.
DThe test is missing an async wait for the button to appear.
Attempts:
2 left
💡 Hint
Check the button's label text and the name option in getByRole.
🧠 Conceptual
expert
2:30remaining
What is the main benefit of using React Testing Library over Enzyme?
Choose the best explanation for why React Testing Library is preferred for testing React components compared to Enzyme.
AReact Testing Library requires less setup because it mocks all network requests automatically.
BReact Testing Library allows shallow rendering which Enzyme does not support.
CReact Testing Library encourages testing components like users interact with them, focusing on accessibility and behavior rather than implementation details.
DReact Testing Library uses snapshot testing exclusively, which Enzyme cannot do.
Attempts:
2 left
💡 Hint
Think about how tests should reflect user experience.

Practice

(1/5)
1. What is the main purpose of React Testing Library in a Next.js project?
easy
A. To manage global state in React applications
B. To style React components with CSS-in-JS
C. To test React components by simulating user interactions and checking visible output
D. To optimize React components for faster rendering

Solution

  1. Step 1: Understand React Testing Library's role

    It focuses on testing components by simulating how users interact with them and what they see.
  2. Step 2: Compare options with this role

    Only To test React components by simulating user interactions and checking visible output describes testing user interactions and visible output, which matches React Testing Library's purpose.
  3. Final Answer:

    To test React components by simulating user interactions and checking visible output -> Option C
  4. Quick Check:

    Testing user behavior = D [OK]
Hint: React Testing Library tests user actions and visible UI [OK]
Common Mistakes:
  • Confusing testing library with styling or state management tools
  • Thinking it optimizes rendering performance
  • Assuming it manages app state
2. Which of the following is the correct way to import the render function from React Testing Library?
easy
A. import { render } from '@testing-library/react';
B. import render from 'react-testing-library';
C. import { render } from 'react-dom';
D. import { render } from 'next/testing';

Solution

  1. Step 1: Identify the official package for React Testing Library

    The correct package is '@testing-library/react' for React Testing Library functions.
  2. Step 2: Check import syntax

    React Testing Library exports render as a named export, so use curly braces around render.
  3. Final Answer:

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

    Named import from '@testing-library/react' = B [OK]
Hint: Use named import from '@testing-library/react' for render [OK]
Common Mistakes:
  • Using default import instead of named import
  • Importing from wrong package like 'react-dom' or 'next/testing'
  • Missing curly braces around render
3. Given this test code snippet, what will screen.getByText('Hello World') return?
import { render, screen } from '@testing-library/react';

function Greeting() {
  return <h1>Hello World</h1>;
}

test('renders greeting text', () => {
  render(<Greeting />);
  const element = screen.getByText('Hello World');
  return element;
});
medium
A. An error because screen is not defined
B. The <h1> element containing 'Hello World'
C. null because 'Hello World' is not found
D. An array of all elements with text 'Hello World'

Solution

  1. Step 1: Understand what render and screen.getByText do

    render displays the component in a virtual DOM; screen.getByText finds the first element with matching text.
  2. Step 2: Check the component output

    Greeting returns <h1>Hello World</h1>, so screen.getByText('Hello World') finds this <h1> element.
  3. Final Answer:

    The <h1> element containing 'Hello World' -> Option B
  4. Quick Check:

    getByText finds matching element = C [OK]
Hint: getByText returns the matching DOM element, not null or array [OK]
Common Mistakes:
  • Thinking getByText returns null if found
  • Confusing screen with undefined variable
  • Assuming getByText returns multiple elements
4. Identify the error in this test code snippet:
import { render, screen, fireEvent } from '@testing-library/react';

function Button() {
  const [count, setCount] = React.useState(0);
  return <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>;
}

test('increments count on click', () => {
  render(<Button />);
  const button = screen.getByRole('button');
  fireEvent.click(button);
  expect(button.textContent).toBe('Clicked 1 times');
});
medium
A. Expect statement should check button.innerHTML
B. Using fireEvent instead of userEvent
C. Incorrect role used in getByRole
D. Missing import of React from 'react'

Solution

  1. Step 1: Check imports for React usage

    The component uses React.useState but React is not imported, causing a runtime error.
  2. Step 2: Verify other parts

    fireEvent.click and getByRole('button') are correct usage; expect checks textContent correctly.
  3. Final Answer:

    Missing import of React from 'react' -> Option D
  4. Quick Check:

    React must be imported to use React.useState = A [OK]
Hint: Always import React when using React APIs like useState [OK]
Common Mistakes:
  • Assuming fireEvent is wrong instead of userEvent
  • Thinking getByRole('button') is incorrect
  • Checking innerHTML instead of textContent
5. You want to test a Next.js component that fetches data on mount and displays it. Which approach correctly integrates React Testing Library with async data fetching?
import { render, screen, waitFor } from '@testing-library/react';
import React from 'react';

function DataDisplay() {
  const [data, setData] = React.useState(null);
  React.useEffect(() => {
    fetch('/api/data').then(res => res.json()).then(setData);
  }, []);
  if (!data) return <div>Loading...</div>;
  return <div>Data: {data.value}</div>;
}

test('shows fetched data', async () => {
  global.fetch = jest.fn(() => Promise.resolve({
    json: () => Promise.resolve({ value: 'Hello' })
  }));
  render(<DataDisplay />);
  await waitFor(() => screen.getByText('Data: Hello'));
  expect(screen.getByText('Data: Hello')).toBeInTheDocument();
});
hard
A. Correctly mocks fetch and waits for async update with waitFor
B. Should use fireEvent to trigger fetch manually
C. Missing cleanup of fetch mock after test
D. Should use getByText without waitFor for async content

Solution

  1. Step 1: Check mocking of fetch

    The test mocks global.fetch to return a resolved promise with expected data, which is correct for simulating API calls.
  2. Step 2: Verify waiting for async UI update

    Using waitFor to wait until the text 'Data: Hello' appears is the right way to handle async rendering in tests.
  3. Final Answer:

    Correctly mocks fetch and waits for async update with waitFor -> Option A
  4. Quick Check:

    Mock fetch + waitFor async UI = A [OK]
Hint: Mock fetch and use waitFor to handle async UI updates [OK]
Common Mistakes:
  • Trying to trigger fetch with fireEvent instead of mocking
  • Not waiting for async content before assertions
  • Forgetting to cleanup mocks (not critical here)
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