Menu

Testing Next.js Applications

Lesson 4: Testing Next.js Applications

Which tests should you write?

Test type Tool Tests Speed
Unit Vitest or Jest Pure functions, validation schemas, utilities Very fast
Component Vitest + React Testing Library Client Components and synchronous Server Components Fast
End-to-end (E2E) Playwright or Cypress Full user journeys in a real browser, including async Server Components Slower

Async Server Components are not yet well supported by unit-test tools, so test them through E2E tests.

Example: unit test with Vitest

// lib/validation.test.ts
import { describe, it, expect } from 'vitest';
import { EnrolSchema } from './validation';

describe('EnrolSchema', () => {
  it('rejects an invalid email', () => {
    const result = EnrolSchema.safeParse({ name: 'Asha', email: 'asha@', courseId: 'c1' });
    expect(result.success).toBe(false);
  });
});

Example: component test

// app/components/LikeButton.test.tsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { LikeButton } from './LikeButton';

it('increments likes on click', async () => {
  render(<LikeButton />);
  await userEvent.click(screen.getByRole('button'));
  expect(screen.getByRole('button')).toHaveTextContent('1');
});

Example: end-to-end with Playwright

// e2e/enrol.spec.ts
import { test, expect } from '@playwright/test';

test('student can enrol in a course', async ({ page }) => {
  await page.goto('/courses/sql');
  await page.getByRole('link', { name: 'Enrol now' }).click();
  await page.getByLabel('Name').fill('Asha R');
  await page.getByLabel('Email').fill('[email protected]');
  await page.getByRole('button', { name: 'Enrol now' }).click();
  await expect(page).toHaveURL(/dashboard/);
});

How it works

  • Vitest runs tests in Node with a simulated DOM (jsdom), so component tests do not need a browser.
  • Playwright starts your app (configure webServer in playwright.config.ts) and drives a real browser.
  • Run E2E tests against a production build to match real behaviour.
  • Next.js 16.3 adds an instant() helper in @next/playwright to assert which content appears immediately during a navigation, catching regressions in loading behaviour.

Common mistakes

Mistake Effect Fix
Unit-testing async Server Components Errors or false confidence Cover them with E2E tests
Selecting elements by CSS class Tests break on style changes Select by role, label, or text
E2E tests against the dev server Slow, flaky results Test a production build
Only testing the happy path Bugs in error handling Test validation errors and permission denials too

Key takeaways

  • Unit-test logic, component-test interactive UI, and E2E-test critical journeys.
  • Prioritise E2E tests for sign-in, enrolment, and payment flows.

Try it: Write one Vitest test for your Zod schema and one Playwright test for the enrolment flow, and run both in CI.


Nextjs Tutorial

J

Jebasta





Get in Touch For Details