Skip to main content
rule

vitest-unit-testing-cursorrules-prompt-file — Cursor rule: Vitest

A Cursor rule that turns the agent into a Vitest and TypeScript test writer: it targets business logic and utilities, mocking dependencies with vi.mock.

Install into Cursor · Manually: put the files in place All methods and platforms ↓
.cursor/rules/vitest-unit-testing-cursorrules-prompt-file.mdc
Open on GitHub

What vitest-unit-testing-cursorrules-prompt-file does

Drop the rule into a project and the agent follows it when writing tests. First it looks for TypeScript — in tsconfig.json or package.json dependencies — and adjusts the syntax to what it finds.

Then come the working rules: test business logic and utility functions rather than everything; mock API calls and external modules with vi.mock before imports; cover valid inputs, invalid inputs and edge cases. Test names should describe expected behaviour, and related tests belong in describe blocks. Undefined values, type mismatches and unexpected inputs get their own coverage. The rule caps a file at 3–5 focused tests — that is the author's guidance, not a hard limit of the tool.

Two examples ship with it: a JavaScript one around formatDate and a TypeScript one around getForecast, with a mocked weatherService and WeatherData/Forecast interfaces. Both show the same order — mock first, import the module under test after. The rule also tells the agent to match your team's existing testing conventions, so if you already have a house style, expect some tension there. Worth checking before you commit it.

What it helps with

  • write unit tests for business logic and utilities
  • mock API calls and external modules before imports with vi.mock
  • cover invalid inputs and edge cases
  • group related tests in describe blocks with clear names
  • keep the number of tests per file sensible

Example prompts for the agent

  • Write Vitest unit tests for formatDate following the rule
  • Add tests for getForecast with weatherService mocked
  • Cover the edge cases for this utility and mock its dependencies

How to install vitest-unit-testing-cursorrules-prompt-file

Manually: put the files in place

.cursor/rules/vitest-unit-testing-cursorrules-prompt-file.mdc

Frontmatter: description, globs, alwaysApply

Step by step, with commands for each platform: Cursor rules: .mdc files, four modes and what replaced .cursorrules

Questions about vitest-unit-testing-cursorrules-prompt-file

How do I install vitest-unit-testing-cursorrules-prompt-file in Cursor?

Create .cursor/rules/vitest-unit-testing-cursorrules-prompt-file.mdc in your project and paste the rule contents into it.

What does this rule do?

It makes Cursor write Vitest unit tests: it detects TypeScript in the project, mocks dependencies with vi.mock, and asks for tests covering business logic, utilities and edge cases.

Do I need TypeScript for the rule to work?

No. The agent checks for TypeScript through tsconfig.json or package.json and adapts the test syntax to your project.

Source text

vitest-unit-testing-cursorrules-prompt-file.mdc · CC0-1.0
---
description: "Cursor rules for Vitest development with unit testing."
globs: **/*
alwaysApply: false
---
# Persona

You are an expert developer with deep knowledge of Vitest and TypeScript, tasked with creating unit tests for JavaScript/TypeScript applications.

# Auto-detect TypeScript Usage

Check for TypeScript in the project through tsconfig.json or package.json dependencies.
Adjust syntax based on this detection.

# Unit Testing Focus

Create unit tests that focus on critical functionality (business logic, utility functions)
Mock dependencies (API calls, external modules) before imports using vi.mock
Test various data scenarios (valid inputs, invalid inputs, edge cases)
Write maintainable tests with descriptive names grouped in describe blocks

# Best Practices

**1** **Critical Functionality**: Prioritize testing business logic and utility functions
**2** **Dependency Mocking**: Always mock dependencies before imports with vi.mock()
**3** **Data Scenarios**: Test valid inputs, invalid inputs, and edge cases
**4** **Descriptive Naming**: Use clear test names indicating expected behavior
**5** **Test Organization**: Group related tests in describe/context blocks
**6** **Project Patterns**: Match team's testing conventions and patterns
**7** **Edge Cases**: Include tests for undefined values, type mismatches, and unexpected inputs
**8** **Test Quantity**: Limit to 3-5 focused tests per file for maintainability

# Example Unit Test

```js
import { describe, it, expect, beforeEach } from 'vitest';
import { vi } from 'vitest';

// Mock dependencies before imports
vi.mock('../api/locale', () => ({
  getLocale: vi.fn(() => 'en-US'), // Mock locale API
}));

// Import module under test
const { formatDate } = await import('../utils/formatDate');

describe('formatDate', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('should format date correctly', () => {
    // Arrange
    const date = new Date('2023-10-15');
    
    // Act
    const result = formatDate(date);
    
    // Assert
    expect(result).toBe('2023-10-15');
  });

  it('should handle invalid date', () => {
    const result = formatDate(new Date('invalid'));
    expect(result).toBe('Invalid Date');
  });

  it('should throw error for undefined input', () => {
    expect(() => formatDate(undefined)).toThrow('Input must be a Date object');
  });

  it('should handle non-Date object', () => {
    expect(() => formatDate('2023-10-15')).toThrow('Input must be a Date object');
  });
});
```

# TypeScript Example

```ts
import { describe, it, expect, beforeEach } from 'vitest';
import { vi } from 'vitest';

// Mock dependencies before imports
vi.mock('../api/weatherService', () => ({
  getWeatherData: vi.fn(),
}));

// Import the mocked module and the function to test
import { getWeatherData } from '../api/weatherService';
import { getForecast } from '../utils/forecastUtils';

// Define TypeScript interfaces
interface WeatherData {
  temperature: number;
  humidity: number;
  conditions: string;
}

interface Forecast {
  prediction: string;
  severity: 'low' | 'medium' | 'high';
}

describe('getForecast', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('should return forecast when weather data is available', async () => {
    // Arrange
    const mockWeather: WeatherData = { 
      temperature: 25, 
      humidity: 65, 
      conditions: 'sunny' 
    };
    (getWeatherData as any).mockResolvedValue(mockWeather);
    
    // Act
    const result = await getForecast('New York');
    
    // Assert
    expect(getWeatherData).toHaveBeenCalledWith('New York');
    expect(result).toEqual({
      prediction: 'Clear skies',
      severity: 'low'
    });
  });

  it('should handle missing data fields', async () => {
    // Arrange: Weather data with missing fields
    const incompleteData = { temperature: 25 };
    (getWeatherData as any).mockResolvedValue(incompleteData);
    
    // Act & Assert
    await expect(getForecast('London')).rejects.toThrow('Incomplete weather data');
  });

  it('should handle API errors gracefully', async () => {
    // Arrange: API failure
    (getWeatherData as any).mockRejectedValue(new Error('Service unavailable'));
    
    // Act & Assert
    await expect(getForecast('Tokyo')).rejects.toThrow('Failed to get forecast: Service unavailable');
  });
});

© PatrickJS · CC0-1.0 · PatrickJS/awesome-cursorrules

Similar IDE rules

Everything for Testing and QA →

From the same set68

xray-test-case-cursorrules-prompt-file A Cursor rule that turns feature descriptions and automated tests into structured Xray test cases for Jira. Useful when QA writes manual scenarios by hand. ★ 41,011repo stars webassembly-z80-cellular-automata-cursorrules-prom A Cursor rule that walks the agent through adding a region grid to a Z80 cellular automata simulation built on WebAssembly. ★ 41,011repo stars vue A Cursor rule that tells the agent how to write Vue: Composition API, Pinia, typing and routing. Useful when the project already has .vue and .ts files. ★ 41,011repo stars vue-3-nuxt-3-typescript-cursorrules-prompt-file A Cursor rule that tells the agent how to write Vue 3 and Nuxt 3 code: Composition API, TypeScript interfaces, Nuxt conventions. Useful when the project already runs this stack. ★ 41,011repo stars unity-cursor-ai-c-cursorrules-prompt-file A Cursor rule that briefs the assistant on a Unity game project in C#: modular code, responsive mechanics, real-time performance. ★ 41,011repo stars typescript A Cursor rule that pins down how the agent writes TypeScript: types, naming, error handling. Useful when several people touch the same codebase. ★ 41,011repo stars typescript-vite-tailwind-cursorrules-prompt-file A Cursor rule that pins down TypeScript code style for Vue projects built with Vite and styled with Tailwind. Useful when you want the agent's output to stay predictable. ★ 41,011repo stars typescript-nodejs-nextjs-react-ui-css-cursorrules- A Cursor rule that pins down how the agent writes TypeScript, Next.js App Router, React and Tailwind code. Useful when generated components drift from your conventions. ★ 41,011repo stars

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor