0
0
NextJSframework~5 mins

Testing server components in NextJS

Choose your learning style9 modes available
Introduction

Testing server components helps ensure they work correctly before showing them to users. It catches mistakes early and keeps your app reliable.

When you want to check if a server component fetches and displays data correctly.
When you update a server component and want to confirm it still works as expected.
When you want to automate checks so your app stays stable during changes.
Syntax
NextJS
import { render } from '@testing-library/react';
import MyServerComponent from './MyServerComponent';

test('renders server component correctly', async () => {
  const { findByText } = render(<MyServerComponent />);
  const element = await findByText('Hello from server');
  expect(element).toBeInTheDocument();
});

Use @testing-library/react to render components in tests.

Server components can be tested like normal React components but remember they run on the server.

Examples
This test checks if the Greeting server component shows the welcome message.
NextJS
import { render } from '@testing-library/react';
import Greeting from './Greeting';

test('shows greeting message', async () => {
  const { findByText } = render(<Greeting />);
  const message = await findByText('Welcome to Next.js!');
  expect(message).toBeInTheDocument();
});
This test verifies that the UserProfile component shows the correct user name.
NextJS
import { render } from '@testing-library/react';
import UserProfile from './UserProfile';

test('displays user name', async () => {
  const { findByText } = render(<UserProfile userId={1} />);
  const name = await findByText('Alice');
  expect(name).toBeInTheDocument();
});
Sample Program

This example shows a simple server component that renders a heading. The test renders it and checks if the heading text appears.

NextJS
import React from 'react';

// Server component that returns a greeting
export default function HelloServer() {
  return <h1>Hello from server</h1>;
}

// Test file: HelloServer.test.js
import { render } from '@testing-library/react';
import HelloServer from './HelloServer';

test('renders HelloServer component', async () => {
  const { findByText } = render(<HelloServer />);
  const heading = await findByText('Hello from server');
  expect(heading).toBeInTheDocument();
});
OutputSuccess
Important Notes

Server components run only on the server, so avoid client-only APIs in them.

Use async testing helpers like findByText to wait for content to appear.

Keep tests small and focused on one behavior at a time.

Summary

Testing server components helps catch errors early and keeps your app stable.

Use @testing-library/react to render and check server components in tests.

Write simple tests that check if expected content appears when the component renders.