IDE-Tools · Foto: Homedust, CC BY 2.0
Jest Unit Testing
Zuletzt aktualisiert:
Typ
Regel
Lizenz
CC0 1.0
Anwendungsfeld
Cursor Rules
Voraussetzungen
Keine besonderen — direkt loslegen.
Jest-Testregel für Cursor: Teststruktur, Mocking- und Coverage-Konventionen.
Original-Beschreibung der Autoren: Cursor rules for Jest development with unit testing.
Die Regel
---
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
// 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: 'john@example.com' };
(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');
});
});
So nutzt du sie
Die Regel kopieren (Button oben) oder als Datei herunterladen und im Projekt unter .cursor/rules/ ablegen — Cursor lädt sie beim nächsten Start automatisch. Ältere Cursor-Versionen lesen alternativ eine einzelne .cursorrules-Datei im Projektstamm; dort einfach den Regel-Text ohne den Kopfblock zwischen den ----Zeilen einfügen.
Der Regel-Text ist englisch — Cursor versteht ihn unabhängig von der Sprache, in der Sie mit dem Editor chatten.
Im Detail
Diese Regel definiert, wie Cursor Jest-Unit-Tests aufbaut: Datei- und Ordnerstruktur, etwa tests-Ordner oder Co-Location, Konventionen für describe/it-Blöcke, wann und wie gemockt werden soll (jest.mock vs. manuelle Mocks) sowie Vorgaben zu Coverage-Zielen. Der Nutzen liegt darin, dass generierte Tests nicht nur „irgendwie grün“ sind, sondern tatsächlich relevante Fälle abdecken und sich konsistent in eine bestehende Testsuite einfügen. Besonders wertvoll für Teams, die bereits eine Jest-Konfiguration haben und verhindern wollen, dass Cursor bei jedem neuen Test ein anderes Muster für Setup, Mocking oder Assertions erfindet.
Praxis-Tipp
Gut kombinierbar mit einer Codequalitätsregel wie javascript-typescript-code-quality, damit Testcode denselben Namens- und Typisierungsstandards folgt wie der Produktivcode.
Lizenz & Quelle
- Lizenz: CC0 1.0
- Quelle: PatrickJS/awesome-cursorrules (GitHub)
Inhalt ansehen (jest-unit-testing.mdc)
Lade …
Erfahrungen & Kommentare.
Funktioniert der Regel bei Ihnen? Tipps, Stolperfallen, Varianten — teilen Sie es mit der Community.
Lade Kommentare …
Passt dazu.
AI Agent Specialist
Cursor-Regel für diszipliniertes, klar abgegrenztes Agenten-Verhalten statt unstrukturierter KI-Antworten.
Alpha Skills Quant Factor Research
Cursor-Regel für methodisch saubere quantitative Faktor-Recherche im Trading-Umfeld.
Android Jetpack Compose
Cursor-Regel für idiomatischen, deklarativen Android-UI-Code mit Jetpack Compose.
