Vitest is a fast and lightweight testing framework that integrates seamlessly with Next.js for efficient unit testing and improved application reliability.
- Delivers fast test execution with modern tooling.
- Supports testing of components and application logic.
- Simplifies debugging through automated testing.
- Improves code quality and maintainability.
Steps to Set Up Vitest Testing in Next.js
Follow the steps given below:
Step 1: Create a New Next.js Application
npx create-next-app@latest vitest-app
cd vitest-app
Step 2: Install Vitest and Testing Dependencies
npm install --save-dev vitest jsdom @testing-library/react @testing-library/jest-dom @vitejs/plugin-reactProject Structure:
vitest-app
│
├── app
│ └── page.js
├── components
│ └── Button.jsx
├── __tests__
│ └── Button.test.jsx
├── vitest.config.js
├── vitest.setup.js
├── public
└── package.json
Step 3: Configure Vitest
Create a vitest.config.js file in the project root.
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
globals: true,
environment: "jsdom",
setupFiles: ["./vitest.setup.js"],
include: ["__tests__/**/*.test.{js,jsx,ts,tsx}"],
},
});
Create a vitest.setup.js file.
import "@testing-library/jest-dom/vitest";Step 4: Create a Sample Component
Filename: components/Button.jsx
const Button = ({ label }) => {
return <button>{label}</button>;
};
export default Button;
Step 5: Create Test Cases
Filename: __tests__/Button.test.jsx
import { render, screen } from "@testing-library/react";
import { describe, test, expect } from "vitest";
import Button from "../components/Button";
describe("Button", () => {
test("renders button text", () => {
render(<Button label="Click Me" />);
expect(
screen.getByText("Click Me")
).toBeInTheDocument();
});
});
Step 6: Update package.json
Add the following script to the package.json file to run the Vitest test suite.
"scripts": {
"test": "vitest"
}
Step 7: Run the Test
Now, run the test using the below command:
npm testOutput:
