Advertisement
Beginner Next.js, Testing Next.js Applications

How do you write a basic unit test for a component in a Next.js application?

Short answer

You typically use a testing library like Jest along with React Testing Library, rendering the component in a test environment and then making assertions about what should appear on the screen or how it should respond to simulated user interactions like clicks.

Save Next.js mock interview
Advertisement
AModel answer
You typically use a testing library like Jest along with React Testing Library, rendering the component in a test environment and then making assertions about what should appear on the screen or how it should respond to simulated user interactions like clicks.
import { render, screen } from '@testing-library/react';
import Button from './Button';

test('renders button with correct text', () => {
  render(<Button>Click me</Button>);
  expect(screen.getByText('Click me')).toBeInTheDocument();
});
Real-world example
A component library tests that its Button component correctly displays the text passed to it, catching any accidental changes to its rendering behavior before they reach production.
Likely follow-ups
  • What is the difference between React Testing Library and Enzyme?
  • How do you test a component that fetches data on mount?
Related topics