Jun 13, 2025
Jest
Testing Library
Next.js
Testing in Next.js: From Setup to Strategy
Overview
Many Next.js tutorials oddly skip over testing. I followed all the steps, built and deployed apps—yet I never wrote a single test.
In contrast, I’ve heard that writing tests is standard practice in real-world development. So, my earlier React + Vite portfolio included tests from the beginning. And, I assumed I could do the same with Next.js.
However, even writing basic tests in a Next.js project turned out to be more complicated than expected.
Next.js introduces unique testing challenges due to its internal architecture, server-side features, and hybrid rendering model. Despite being familiar with React testing, I had to relearn how to configure and execute tests from scratch.
What I Learned
Setting Up Tests in Next.js
- Jest + Testing Library is the standard setup for React/Next.js testing
- However, Next.js requires
next/jestto properly transform internal modules -
Tests run in a
jsdomenvironment (a simulated browser), which means:- API Routes aren’t available during test execution
fetchcalls must be mocked unless you’re doing integration testing
-
In addition to common testing libraries, some supporting packages are needed:
-
jest-environment-jsdom,@types/jest,ts-node
-
-
Key config files:
-
jest.config.ts,jest.setup.ts,tsconfig.json
-
-
I learned a practical convention for organizing test files:
- __mocks__/ for mocking framework-specific modules like next/image
- tests/ for integration tests that include API Routes and sanity checks
-
I learned about the idea of a sanity test:
- A minimal test used to confirm the test runner itself is working
- Useful before writing any "real" test code—especially to debug the initial setup
Next.js - Specific Considerations
next/imageandnext/linkmust be manually mocked in Jest-
Separate testing strategies for pages and components:
- Pages often contain multiple components → best suited for integration tests
- Components with internal state or behavior → unit tests
- When using
useRouter()or similar hooks, mock them in tests -
If a component uses
fetchto access an API Route:- In unit tests: mock the
fetchcall - In integration tests, spin up a fake Next.js server with
createServer()and test withsupertest
- In unit tests: mock the
-
Testing Server Actions
- Server Actios are not fetch-based APIs and can't be accessed like API Routes
- Write unit tests by manually creating
FormDataand calling the function - Test UI integration via E2E tools (like Playwright)
