xiaohongshu
xiaohongshu
Add unit tests for component or function: $ARGUMENTS
Full skill instructions
I'll create comprehensive unit tests for $ARGUMENTS following the project's testing patterns.
This will include:
Let's begin!
First, I'll locate the file to test.
For React components:
# Check components directory
if [ -f "expense-tracker-ai/components/$ARGUMENTS.tsx" ]; then
SOURCE_FILE="expense-tracker-ai/components/$ARGUMENTS.tsx"
TEST_FILE="expense-tracker-ai/components/$ARGUMENTS.test.tsx"
FILE_TYPE="component"
echo "✅ Found component: $SOURCE_FILE"
elif [ -f "expense-tracker-ai/components/$ARGUMENTS.ts" ]; then
SOURCE_FILE="expense-tracker-ai/components/$ARGUMENTS.ts"
TEST_FILE="expense-tracker-ai/components/$ARGUMENTS.test.ts"
FILE_TYPE="component"
echo "✅ Found component: $SOURCE_FILE"
fi
For utility functions:
# Check lib directory
if [ -f "expense-tracker-ai/lib/$ARGUMENTS.ts" ]; then
SOURCE_FILE="expense-tracker-ai/lib/$ARGUMENTS.ts"
TEST_FILE="expense-tracker-ai/lib/$ARGUMENTS.test.ts"
FILE_TYPE="utility"
echo "✅ Found utility: $SOURCE_FILE"
fi
For app pages:
# Check app directory
if [ -f "expense-tracker-ai/app/$ARGUMENTS.tsx" ]; then
SOURCE_FILE="expense-tracker-ai/app/$ARGUMENTS.tsx"
TEST_FILE="expense-tracker-ai/app/$ARGUMENTS.test.tsx"
FILE_TYPE="page"
echo "✅ Found page: $SOURCE_FILE"
fi
If file not found:
if [ -z "$SOURCE_FILE" ]; then
echo "❌ Error: Could not find $ARGUMENTS"
echo ""
echo "Available components:"
ls -1 expense-tracker-ai/components/*.tsx 2>/dev/null | sed 's/.*\///' | sed 's/\.tsx$//'
echo ""
echo "Available utilities:"
ls -1 expense-tracker-ai/lib/*.ts 2>/dev/null | sed 's/.*\///' | sed 's/\.ts$//'
exit 1
fi
Before creating a new test file, check if one already exists:
if [ -f "$TEST_FILE" ]; then
echo "⚠️ Test file already exists: $TEST_FILE"
echo ""
echo "Options:"
echo "1. Update existing tests (add new test cases)"
echo "2. Replace existing tests (overwrite file)"
echo "3. Cancel (leave existing tests unchanged)"
echo ""
echo "What would you like to do?"
# Wait for user decision
else
echo "✅ No existing test file - will create new one"
fi
Read the source file to understand what needs testing:
# Read the source file to understand its structure
echo "Analyzing $SOURCE_FILE..."
# Look for key patterns:
# - Export statements (what's being exported)
# - Function definitions (what functions exist)
# - Props interfaces (what props are expected)
# - State hooks (what state is managed)
Use the Read tool to examine the source file and identify:
Create a test file based on the file type:
For React Components:
import { render, screen, fireEvent } from '@testing-library/react';
import { ComponentName } from './ComponentName';
describe('ComponentName', () => {
// Setup and teardown
beforeEach(() => {
// Clear any mocks or state before each test
});
afterEach(() => {
// Cleanup after each test
});
// Happy path tests
test('should render correctly', () => {
render(<ComponentName />);
expect(screen.getByTestId('component-name')).toBeInTheDocument();
});
test('should display expected content', () => {
render(<ComponentName />);
// Add specific content checks based on component
});
// Interaction tests
test('should handle user interaction', () => {
render(<ComponentName />);
const button = screen.getByRole('button', { name: /button text/i });
fireEvent.click(button);
// Assert expected behavior after interaction
});
// Props tests
test('should render with custom props', () => {
const mockProps = {
// Define test props
};
render(<ComponentName {...mockProps} />);
// Assert component renders correctly with props
});
// Edge cases
test('should handle empty state', () => {
render(<ComponentName />);
// Assert behavior with no data
});
test('should handle error state', () => {
// Test error scenarios
});
// Accessibility tests
test('should be accessible', () => {
const { container } = render(<ComponentName />);
// Basic accessibility checks
// Consider using @axe-core/react for comprehensive checks
});
});
For Utility Functions:
import { functionName } from './fileName';
describe('functionName', () => {
// Happy path tests
test('should return expected output for valid input', () => {
const result = functionName(validInput);
expect(result).toBe(expectedOutput);
});
// Edge cases
test('should handle edge case: empty input', () => {
const result = functionName('');
expect(result).toBe(expectedEmptyOutput);
});
test('should handle edge case: null input', () => {
const result = functionName(null);
expect(result).toBe(expectedNullOutput);
});
test('should handle edge case: undefined input', () => {
const result = functionName(undefined);
expect(result).toBe(expectedUndefinedOutput);
});
// Boundary conditions
test('should handle minimum value', () => {
const result = functionName(minValue);
expect(result).toBe(expectedMinOutput);
});
test('should handle maximum value', () => {
const result = functionName(maxValue);
expect(result).toBe(expectedMaxOutput);
});
// Error handling
test('should throw error for invalid input', () => {
expect(() => functionName(invalidInput)).toThrow();
});
});
Based on the source file analysis, customize the test template:
For components with props:
For components with state:
For components with events:
For utility functions:
Write the customized test template to the test file using the Write tool.
Important conventions:
data-testid attributes for stable selectorsdescribe blocksExecute the test suite to verify the tests work:
cd expense-tracker-ai
# Run just the new test file
npm test -- $ARGUMENTS.test
# If tests fail, run in watch mode for debugging
npm run test:watch -- $ARGUMENTS.test
If tests fail, categorize and address the issues:
Type 1: Test Implementation Issues
# Debug in watch mode
npm run test:watch -- $ARGUMENTS.test
# Run with verbose output
npm test -- --verbose $ARGUMENTS.test
Type 2: Missing Test Infrastructure
data-testid in component → Add to source fileType 3: Source Code Issues
Resolution approach:
Ensure tests meet quality standards:
Coverage checklist:
Quality checklist:
data-testid, not CSS classes)Generate a summary of what was created:
✅ Unit Tests Created Successfully
📊 Summary:
- Source file: $SOURCE_FILE
- Test file: $TEST_FILE
- File type: $FILE_TYPE
- Test cases: [count]
- All tests passing: ✓
📝 Test Coverage:
- Happy path scenarios ([count] tests)
- Edge cases ([count] tests)
- Error handling ([count] tests)
- User interactions ([count] tests - for components)
- Props variations ([count] tests - for components)
✅ Test Quality:
- Independent tests: ✓
- Stable selectors: ✓
- Descriptive names: ✓
- Project conventions: ✓
💡 Next Steps:
- Run full test suite: npm test
- Check coverage: npm test -- --coverage
- Run in watch mode: npm run test:watch
# Add tests for ExpenseForm component
add-test ExpenseForm
Expected output:
✅ Found component: expense-tracker-ai/components/ExpenseForm.tsx
✅ No existing test file - will create new one
Analyzing expense-tracker-ai/components/ExpenseForm.tsx...
Creating test file with coverage for:
- Form rendering
- Input validation
- Form submission
- Error states
- Props handling
✅ Unit Tests Created Successfully
📊 Summary:
- Source file: expense-tracker-ai/components/ExpenseForm.tsx
- Test file: expense-tracker-ai/components/ExpenseForm.test.tsx
- File type: component
- Test cases: 12
- All tests passing: ✓
# Add tests for getCategoryColor utility
add-test getCategoryColor
Expected output:
✅ Found utility: expense-tracker-ai/lib/utils.ts
Analyzing getCategoryColor function...
Creating test file with coverage for:
- Valid category names
- Hash consistency
- Edge cases (empty, null)
- Return value format
✅ Unit Tests Created Successfully
📊 Summary:
- Source file: expense-tracker-ai/lib/utils.ts
- Test file: expense-tracker-ai/lib/utils.test.ts
- File type: utility
- Test cases: 8
- All tests passing: ✓
This skill follows the expense tracker app's testing conventions:
From jest.setup.js:
// ResizeObserver mock for Recharts components
global.ResizeObserver = class ResizeObserver {
observe() {}
unobserve() {}
disconnect() {}
};
localStorage mocking:
beforeEach(() => {
const localStorageMock = {
getItem: jest.fn(),
setItem: jest.fn(),
clear: jest.fn(),
};
global.localStorage = localStorageMock as any;
});
Testing Library selectors:
// Prefer data-testid
screen.getByTestId('submit-button')
// Use semantic queries
screen.getByRole('button', { name: /submit/i })
// Avoid brittle selectors
// ❌ screen.getByClassName('btn-primary')
// ❌ container.querySelector('.form button:nth-child(2)')
Async testing:
test('should load data asynchronously', async () => {
render(<Component />);
// Wait for element to appear
const element = await screen.findByTestId('loaded-data');
expect(element).toBeInTheDocument();
});
Error: Cannot find module '@testing-library/react'
Solution:
cd expense-tracker-ai
npm install --save-dev @testing-library/react @testing-library/jest-dom
Error: ReferenceError: ResizeObserver is not defined
Solution: Already handled in jest.setup.js. If error persists:
# Verify jest.setup.js is configured in jest.config.js
cat jest.config.js | grep setupFilesAfterEnv
Error: Type error: Cannot find name 'describe'
Solution:
# Install Jest types
npm install --save-dev @types/jest
# Verify tsconfig.json includes jest types
cat tsconfig.json | grep jest
Symptom: Tests pass but don't catch obvious bugs
Solution: Review assertions:
// ❌ Weak test (always passes)
test('should work', () => {
const result = someFunction();
expect(result).toBeDefined();
});
// ✅ Strong test (validates actual behavior)
test('should return correct calculation', () => {
const result = calculateTotal([10, 20, 30]);
expect(result).toBe(60);
});
xiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience