Install and Use Jest for Unit Testing in Next.js 15
Writing Jest unit tests in Next.js 15 ensures your application remains reliable and maintainable. This guide covers setting up Jest, writing effective test cases, and integrating it with Next.js features to improve code quality and stability.
Why We Need Unit Tests
Catch Bugs Early: Unit tests help identify issues in individual components and functions before they reach production, reducing debugging time.
Improve Code Quality: Writing tests encourages better coding practices, leading to cleaner and more maintainable code.
Safe Refactoring: With a solid test suite, you can confidently modify or refactor code, knowing existing functionality won’t break.
Enhance Developer Confidence: Developers can make changes or add new features without fear of unintentionally breaking the app.
Maintain Stability in Next.js 15: Next.js applications often involve API routes, components, and server-side logic. Unit tests ensure these elements function correctly even as the app evolves.
Reduce Manual Effort & Speed Up Development: Automated testing saves time compared to manual testing, leading to faster deployment and a more efficient development workflow.
1. Install Dependencies
Run the following command to install Jest and related libraries:
Use Yarn
shellyarn add -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
or Npm
shellnpm install -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
2. Configure Jest
Create a jest.config.ts file in the root of your project:
js/** * For a detailed explanation regarding each configuration property, visit: * https://jestjs.io/docs/configuration */ import nextJest from "next/jest.js"; import type { Config } from "jest"; const createJestConfig = nextJest({ // Provide the path to your Next.js app to load next.config.js and .env files in your test environment dir: "./", }); const config: Config = { // Automatically clear mock calls, instances, contexts and results before every test clearMocks: true, // Indicates whether the coverage information should be collected while executing the test // collectCoverage: true, // The directory where Jest should output its coverage files coverageDirectory: "coverage", // Indicates which provider should be used to instrument code for coverage coverageProvider: "v8", // The test environment that will be used for testing testEnvironment: "jsdom", // The paths to modules that run some code to configure or set up the testing environment before each test // https://github.com/NickColley/jest-axe/issues/147#issuecomment-758804533 setupFilesAfterEnv: ["./jest.setup.ts"], }; export default createJestConfig(config);
3. Setup Jest
Create a jest.setup.ts file in the root of your project:
jsimport "@testing-library/jest-dom";
This ensures that Jest can use custom matchers like .toBeInTheDocument().
4. Add Jest Script to package.json
json"scripts": { "test": "jest", "test-coverage": "jest --coverage", }
5. Write a Sample Test
Create a test file inside tests folder (at root of source code) or alongside your component (e.g., Button.test.tsx):
jsximport "@testing-library/jest-dom"; import { render, screen } from "@testing-library/react"; import Button from "@/components/common/Button"; test("renders button with text", () => { render(<Button>Click me</Button>); expect(screen.getByText("Click me")).toBeInTheDocument(); });
You can copy my Button component (for quickly testing):
jsximport React from "react"; const Button = ({ children, ...props }: { children: React.ReactNode }) => { return ( <button {...(props as React.ComponentPropsWithoutRef<"button">)}> {children} </button> ); }; export default Button;
6. Run the tests
shellyarn test
or
shellnpm run test
The output is:

If you want to show the coverage table:
shellyarn test-coverage

Notes: You can get more coverage info in coverage folder (at the root of source code which is created when you run yarn test-coverage).

7. Bonus: Run the specific uni-test file
shellyarn test Button.test.tsx
8. Some installing issues:
If you get the error when run test:
shellError [ERR_REQUIRE_ESM]: require() of ES Module /home/tuanh/me/build2earn-next15/node_modules/strip-ansi/index.js from /home/tuanh/me/build2earn-next15/node_modules/string-width/index.js not supported. Instead change the require of /home/tuanh/me/build2earn-next15/node_modules/strip-ansi/index.js in /home/tuanh/me/build2earn-next15/node_modules/string-width/index.js to a dynamic import() which is available in all CommonJS modules.
Please remove the yarn.lock (packages.lock) file and node_modules folder. After that, reinstall dependencies:
jsonyarn
or
jsonnpm install