---
description: This rule explains the guidelines for writing Vitest tests for Next.js applications.
globs: *
alwaysApply: false
---
# Testing Guidelines
## Testing Framework
- `vitest` is used for testing
- Tests are colocated next to the tested file
- Example: `dir/format.ts` and `dir/format.test.ts`
## Common Mocks
### Server-Only Mock
```ts
vi.mock("server-only", () => ({}));
```
### Prisma Mock
```ts
import { beforeEach } from "vitest";
import prisma from "@/utils/__mocks__/prisma";
vi.mock("@/utils/prisma");
describe("example", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("test", async () => {
prisma.group.findMany.mockResolvedValue([]);
});
});
```
## Best Practices
- Each test should be independent
- Use descriptive test names
- Mock external dependencies
- Clean up mocks between tests
- Avoid testing implementation details
The Vitest Testing rule provides guidance for writing effective Vitest tests in Next.js applications. It outlines the testing framework setup, common mocking patterns, and best practices to ensure your tests are robust and maintainable.
This rule serves as a reference guide for developers working with Vitest in a Next.js environment. It explains the testing structure, provides code snippets for common mocking scenarios, and offers best practices to follow when writing tests.
The rule establishes that Vitest is the chosen testing framework for the project and enforces a specific file organization pattern. Test files should be colocated with the files they're testing. For example, if you have a utility function in dir/format.ts
, its corresponding test file should be named dir/format.test.ts
.
The rule provides ready-to-use code snippets for frequently needed mocks:
vi.mock("server-only", () => ({}));
import { beforeEach } from "vitest";
import prisma from "@/utils/__mocks__/prisma";
vi.mock("@/utils/prisma");
describe("example", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("test", async () => {
prisma.group.findMany.mockResolvedValue([]);
});
});
The rule emphasizes several important testing principles:
This rule is stored in the file vitest-testing.mdc
within your project's .cursor/rules
directory. Since the rule has a glob pattern of *
, it will be automatically attached when working with any file in your project. This means the AI will have access to these testing guidelines whenever you're interacting with it in Cursor.
You can also manually invoke this rule by typing @vitest-testing
in the Cmd-K prompt or chat interface if you specifically want to reference these testing guidelines during a conversation with the AI.
This rule is particularly useful when:
Remember that well-structured tests not only verify your code works as expected but also serve as documentation and facilitate refactoring with confidence.