Skip to main content
rule

jest-unit-testing-cursorrules-prompt-file — Cursor rule setup guide

Guides Cursor to generate structured Jest unit tests in JavaScript and TypeScript. Enforces dependency mocking before imports and covers edge cases.

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

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

This rule directs Cursor to build unit test suites for business logic and helper functions with Jest. The assistant scans for tsconfig.json or TypeScript dependencies inside package.json to pick the right syntax. Tests are grouped into describe blocks, resetting mocks via beforeEach with jest.clearAllMocks().

External modules and network calls are mocked with jest.mock() strictly before importing the tested module. The prompt caps test quantity to 3–5 focused cases per file, verifying valid data alongside null or unexpected types.

Without a tsconfig.json file or TypeScript packages in package.json, the generator defaults to plain JavaScript syntax.

What it helps with

  • generate unit tests with jest.mock() placed before module imports
  • test edge cases including null, undefined, and incorrect data types
  • limit test quantity to 3–5 focused assertions per file
  • switch automatically between TypeScript and JavaScript syntax

Example prompts for the agent

  • Write Jest unit tests for src/utils/calculateTotal.js covering valid and invalid inputs
  • Create tests for getUserData in src/utils/userUtils.ts and mock external API calls
  • Add Jest tests for network error handling and null inputs in src/services/billing.ts

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

Manually: put the files in place

.cursor/rules/jest-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 jest-unit-testing-cursorrules-prompt-file

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

Add the rule content to .cursor/rules/jest-unit-testing-cursorrules-prompt-file.mdc in your workspace root.

What does jest-unit-testing-cursorrules-prompt-file do?

It guides the IDE to write clean Jest unit tests, place mock calls before imports, and test input edge cases.

How many test cases does this rule generate per file?

The rule restricts output to 3–5 focused tests per file to keep the suite maintainable.

Source text

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

Similar IDE rules

All IDE rules for Testing and QA →

From the same set210

kubernetes-mkdocs-documentation-cursorrules-prompt A Cursor rule that turns the agent into a technical writer for Kubernetes and cloud native docs built with Markdown and MkDocs. ★ 41,024repo stars kotlin-springboot-best-practices-cursorrules-prompt-file A Cursor rule for Kotlin and Spring Boot projects. It enforces layered package structure, constructor injection, and idiomatic Kotlin conventions. ★ 41,024repo stars kotlin-ktor-development-cursorrules-prompt-file This Cursor rule guides Kotlin projects built with Ktor. Use it when shaping API layers, feature folders, error handling, and tests. ★ 41,024repo stars knative-istio-typesense-gpu-cursorrules-prompt-fil A Cursor rule that turns the assistant into a helper for serverless projects built on Knative with Istio, Typesense and HTMX. Useful when your search app runs on that stack. ★ 41,024repo stars javascript-typescript-code-quality-cursorrules-pro A Cursor rule for cleaner JavaScript and TypeScript work. It guides code structure, comments, function order, and narrowly scoped edits. ★ 41,024repo stars javascript-chrome-apis-cursorrules-prompt-file A Cursor rule that points the AI agent at Chrome extension work: manifest, architecture, Chrome API usage. ★ 41,024repo stars javascript-astro-tailwind-css-cursorrules-prompt-f Cursor rule for Astro and Tailwind CSS projects. Enforces clean component composition, static page generation, and disciplined island hydration. ★ 41,024repo stars java-springboot-jpa-cursorrules-prompt-file This rule guides Cursor when building Java Spring Boot projects with JPA, DTOs, and layered APIs. Use it when generated code should follow a fixed structure. ★ 41,024repo 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