Next.js › Testing Next.js Applications
How would you test a server component that fetches data asynchronously?
IntermediateAnswer
Since server components are async functions, you can call them directly in a test environment, await their result, and then check the returned output, though many teams also rely more heavily on integration or end to end tests for server components since they are tightly coupled to the server environment and data fetching.
test('renders posts from server component', async () => {
const jsx = await ProductPage({ params: { id: '1' } });
render(jsx);
expect(screen.getByText('Product Name')).toBeInTheDocument();
});Real-world example A team writes a test that calls their product page server component directly, awaiting its result and verifying the correct product name appears in the rendered output.