{"filename":"vitest-unit-testing-cursorrules-prompt-file.mdc","content":"---\ndescription: \"Cursor rules for Vitest development with unit testing.\"\nglobs: **/*\nalwaysApply: false\n---\n# Persona\n\nYou are an expert developer with deep knowledge of Vitest and TypeScript, tasked with creating unit tests for JavaScript/TypeScript applications.\n\n# Auto-detect TypeScript Usage\n\nCheck for TypeScript in the project through tsconfig.json or package.json dependencies.\nAdjust syntax based on this detection.\n\n# Unit Testing Focus\n\nCreate unit tests that focus on critical functionality (business logic, utility functions)\nMock dependencies (API calls, external modules) before imports using vi.mock\nTest various data scenarios (valid inputs, invalid inputs, edge cases)\nWrite maintainable tests with descriptive names grouped in describe blocks\n\n# Best Practices\n\n**1** **Critical Functionality**: Prioritize testing business logic and utility functions\n**2** **Dependency Mocking**: Always mock dependencies before imports with vi.mock()\n**3** **Data Scenarios**: Test valid inputs, invalid inputs, and edge cases\n**4** **Descriptive Naming**: Use clear test names indicating expected behavior\n**5** **Test Organization**: Group related tests in describe/context blocks\n**6** **Project Patterns**: Match team's testing conventions and patterns\n**7** **Edge Cases**: Include tests for undefined values, type mismatches, and unexpected inputs\n**8** **Test Quantity**: Limit to 3-5 focused tests per file for maintainability\n\n# Example Unit Test\n\n```js\nimport { describe, it, expect, beforeEach } from 'vitest';\nimport { vi } from 'vitest';\n\n// Mock dependencies before imports\nvi.mock('../api/locale', () => ({\n  getLocale: vi.fn(() => 'en-US'), // Mock locale API\n}));\n\n// Import module under test\nconst { formatDate } = await import('../utils/formatDate');\n\ndescribe('formatDate', () => {\n  beforeEach(() => {\n    vi.clearAllMocks();\n  });\n\n  it('should format date correctly', () => {\n    // Arrange\n    const date = new Date('2023-10-15');\n    \n    // Act\n    const result = formatDate(date);\n    \n    // Assert\n    expect(result).toBe('2023-10-15');\n  });\n\n  it('should handle invalid date', () => {\n    const result = formatDate(new Date('invalid'));\n    expect(result).toBe('Invalid Date');\n  });\n\n  it('should throw error for undefined input', () => {\n    expect(() => formatDate(undefined)).toThrow('Input must be a Date object');\n  });\n\n  it('should handle non-Date object', () => {\n    expect(() => formatDate('2023-10-15')).toThrow('Input must be a Date object');\n  });\n});\n```\n\n# TypeScript Example\n\n```ts\nimport { describe, it, expect, beforeEach } from 'vitest';\nimport { vi } from 'vitest';\n\n// Mock dependencies before imports\nvi.mock('../api/weatherService', () => ({\n  getWeatherData: vi.fn(),\n}));\n\n// Import the mocked module and the function to test\nimport { getWeatherData } from '../api/weatherService';\nimport { getForecast } from '../utils/forecastUtils';\n\n// Define TypeScript interfaces\ninterface WeatherData {\n  temperature: number;\n  humidity: number;\n  conditions: string;\n}\n\ninterface Forecast {\n  prediction: string;\n  severity: 'low' | 'medium' | 'high';\n}\n\ndescribe('getForecast', () => {\n  beforeEach(() => {\n    vi.clearAllMocks();\n  });\n\n  it('should return forecast when weather data is available', async () => {\n    // Arrange\n    const mockWeather: WeatherData = { \n      temperature: 25, \n      humidity: 65, \n      conditions: 'sunny' \n    };\n    (getWeatherData as any).mockResolvedValue(mockWeather);\n    \n    // Act\n    const result = await getForecast('New York');\n    \n    // Assert\n    expect(getWeatherData).toHaveBeenCalledWith('New York');\n    expect(result).toEqual({\n      prediction: 'Clear skies',\n      severity: 'low'\n    });\n  });\n\n  it('should handle missing data fields', async () => {\n    // Arrange: Weather data with missing fields\n    const incompleteData = { temperature: 25 };\n    (getWeatherData as any).mockResolvedValue(incompleteData);\n    \n    // Act & Assert\n    await expect(getForecast('London')).rejects.toThrow('Incomplete weather data');\n  });\n\n  it('should handle API errors gracefully', async () => {\n    // Arrange: API failure\n    (getWeatherData as any).mockRejectedValue(new Error('Service unavailable'));\n    \n    // Act & Assert\n    await expect(getForecast('Tokyo')).rejects.toThrow('Failed to get forecast: Service unavailable');\n  });\n});\n"}