0
0
NextJSframework~30 mins

Testing client components in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Testing Client Components in Next.js
📖 Scenario: You are building a simple Next.js client component that shows a counter with increment and decrement buttons. You want to write tests to check that the buttons update the counter correctly.
🎯 Goal: Build a client component with a counter and two buttons, then write tests to verify the counter increments and decrements as expected.
📋 What You'll Learn
Create a client component with a counter state starting at 0
Add two buttons labeled 'Increment' and 'Decrement'
Write a test to check the initial counter value is 0
Write tests to check clicking 'Increment' increases the counter by 1
Write tests to check clicking 'Decrement' decreases the counter by 1
💡 Why This Matters
🌍 Real World
Testing client components ensures your interactive UI works correctly before users see it. This prevents bugs and improves user experience.
💼 Career
Front-end developers often write tests for React or Next.js components to maintain code quality and catch errors early in development.
Progress0 / 4 steps
1
Create the Counter Client Component
Create a file Counter.jsx with a React client component called Counter. Inside it, use useState to create a state variable count initialized to 0. Render a <div> that displays the text Count: {count}.
NextJS
Need a hint?

Remember to add "use client"; at the top to make it a client component.

2
Add Increment and Decrement Buttons
In Counter.jsx, add two <button> elements inside the <div>. One button should have the text Increment and call setCount(count + 1) on click. The other button should have the text Decrement and call setCount(count - 1) on click.
NextJS
Need a hint?

Use onClick handlers on buttons to update the count state.

3
Write a Test for Initial Counter Value
Create a test file Counter.test.jsx. Import render and screen from @testing-library/react and import the Counter component. Write a test named "shows initial count as 0" that renders <Counter /> and checks that the text Count: 0 is in the document.
NextJS
Need a hint?

Use screen.getByText to find the text and expect(...).toBeInTheDocument() to check it exists.

4
Write Tests for Increment and Decrement Buttons
In Counter.test.jsx, add two tests. The first test named "increments count when Increment button clicked" should render <Counter />, click the Increment button using screen.getByText and fireEvent.click, then check the text updates to Count: 1. The second test named "decrements count when Decrement button clicked" should do the same but click the Decrement button and check the text updates to Count: -1.
NextJS
Need a hint?

Use fireEvent.click to simulate button clicks and check the updated text.