jest-unit-testing-cursorrules-prompt-file — правило для Cursor
Настраивает Cursor на создание модульных тестов с Jest. Правило следит за объявлением моков до импортов и проверкой граничных значений.
.cursor/rules/jest-unit-testing-cursorrules-prompt-file.mdcЧто делает jest-unit-testing-cursorrules-prompt-file
Правило задаёт стандарты написания юнит-тестов на Jest для JavaScript и TypeScript. Модель проверяет наличие tsconfig.json или зависимостей в package.json, чтобы сразу выбрать нужный синтаксис. Тесты группируются в блоки describe, а перед каждым прогоном очищаются моки вызовом jest.clearAllMocks().
Основное внимание уделяется бизнес-логике и вспомогательным функциям. Внешние зависимости и сетевые вызовы мокаются строго до импорта тестируемого кода через jest.mock(). На один файл генератор держит лимит в 3–5 тестов, чтобы набор оставался обозримым.
Без tsconfig.json или зависимостей в package.json агент сгенерирует код на обычном JavaScript.
Какие задачи решает
- сгенерировать Jest-тесты с вызовом jest.mock() до импортов
- проверить работу логики на значениях null, undefined и ошибочных типах
- ограничить число тестов до 3–5 проверок на файл для простоты поддержки
- автоматически переключить синтаксис на TypeScript при наличии tsconfig.json
Примеры запросов агенту
- Напиши юнит-тесты на Jest для
src/utils/calculateTotal.jsс проверкой граничных значений - Покрой тестами функцию
getUserDataвsrc/utils/userUtils.ts, замокай вызовы API - Добавь тесты на Jest для обработки сетевых ошибок в
src/services/billing.ts
Как установить jest-unit-testing-cursorrules-prompt-file
Вручную: положить файлы
.cursor/rules/jest-unit-testing-cursorrules-prompt-file.mdcВо frontmatter: description, globs, alwaysApply
Вручную: положить файлы
.claude/rules/jest-unit-testing-cursorrules-prompt-file.mdПоле paths во frontmatter ограничивает файлы: globs из источника → paths
AGENTS.md
Codex читает AGENTS.md: вставьте текст правила туда
Вручную: положить файлы
.github/instructions/jest-unit-testing-cursorrules-prompt-file.instructions.mdПоле applyTo задаёт, к каким файлам применять: globs из источника → applyTo
Вручную: положить файлы
.devin/rules/jest-unit-testing-cursorrules-prompt-file.mdВручную: положить файлы
.clinerules/jest-unit-testing-cursorrules-prompt-file.mdПо шагам, с командами для каждой платформы: Cursor rules: файлы .mdc, четыре режима и замена .cursorrules
Вопросы о jest-unit-testing-cursorrules-prompt-file
Как установить jest-unit-testing-cursorrules-prompt-file в Cursor?
Сохраните правило в файл .cursor/rules/jest-unit-testing-cursorrules-prompt-file.mdc в корне вашего проекта.
Что делает jest-unit-testing-cursorrules-prompt-file?
Оно заставляет Cursor писать лаконичные Jest-тесты, объявлять jest.mock() строго перед импортом модулей и проверять граничные случаи.
Сколько тестов правило создаёт на один файл?
Инструкция задаёт ограничение в 3–5 сфокусированных проверок на файл, чтобы тесты было легко поддерживать.
Исходный текст
jest-unit-testing-cursorrules-prompt-file.mdc · CC0-1.0
---
description: "Cursor rules for Jest development with unit testing."
globs: **/*
alwaysApply: false
---
# Persona
You are an expert developer with deep knowledge of Jest 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
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 jest.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 null values, undefined, and unexpected types
**8** **Test Quantity**: Limit to 3-5 focused tests per file for maintainability
# Example Unit Test
```js
// Mock dependencies before imports
jest.mock('../api/taxRate', () => ({
getTaxRate: jest.fn(() => 0.1), // Mock tax rate as 10%
}));
// Import module under test
const { calculateTotal } = require('../utils/calculateTotal');
describe('calculateTotal', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('should calculate total for valid items with tax', () => {
// Arrange
const items = [{ price: 10, quantity: 2 }, { price: 20, quantity: 1 }];
// Act
const result = calculateTotal(items);
// Assert
expect(result).toBe(44); // (10 * 2 + 20 * 1) * 1.1 (tax) = 44
});
it('should handle empty array', () => {
const result = calculateTotal([]);
expect(result).toBe(0);
});
it('should throw error for invalid item data', () => {
const items = [{ price: 'invalid', quantity: 1 }];
expect(() => calculateTotal(items)).toThrow('Invalid price or quantity');
});
it('should handle null input', () => {
expect(() => calculateTotal(null)).toThrow('Items must be an array');
});
});
```
# TypeScript Example
```ts
// Mock dependencies before imports
jest.mock('../api/userService', () => ({
fetchUser: jest.fn(),
}));
// Import the mocked module and the function to test
import { fetchUser } from '../api/userService';
import { getUserData } from '../utils/userUtils';
// Define TypeScript interfaces
interface User {
id: number;
name: string;
email: string;
}
describe('getUserData', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('should return user data when fetch is successful', async () => {
// Arrange
const mockUser: User = { id: 1, name: 'John Doe', email: '[email protected]' };
(fetchUser as jest.Mock).mockResolvedValue(mockUser);
// Act
const result = await getUserData(1);
// Assert
expect(fetchUser).toHaveBeenCalledWith(1);
expect(result).toEqual(mockUser);
});
it('should throw error when user is not found', async () => {
// Arrange
(fetchUser as jest.Mock).mockResolvedValue(null);
// Act & Assert
await expect(getUserData(999)).rejects.toThrow('User not found');
});
it('should handle API errors gracefully', async () => {
// Arrange
(fetchUser as jest.Mock).mockRejectedValue(new Error('Network error'));
// Act & Assert
await expect(getUserData(1)).rejects.toThrow('Failed to fetch user: Network error');
});
});
© PatrickJS · CC0-1.0 · PatrickJS/awesome-cursorrules