xiaohongshu
xiaohongshu
generate-test
Generate Jest test suite with mocks and common test cases. Use when creating tests for components, repositories, or API routes.
Full skill instructions
Generate a Jest test suite following Health Tracker 9000 testing patterns.
When user requests to create tests, ask for:
Based on src/__tests__/components/forms/MealLogForm.test.tsx pattern.
Create file: src/__tests__/{target-type}/{location}/{TargetName}.test.tsx
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { FormName } from '@/components/forms/FormName';
import { useHealthStore } from '@/lib/store/healthStore';
// Mock the store
jest.mock('@/lib/store/healthStore');
jest.mock('sonner', () => ({
toast: {
success: jest.fn(),
error: jest.fn(),
info: jest.fn(),
},
}));
const mockAddItem = jest.fn();
describe('FormName', () => {
beforeEach(() => {
jest.clearAllMocks();
(useHealthStore as jest.Mock).mockReturnValue({
addItem: mockAddItem,
isLoading: false,
});
});
it('renders the form correctly', () => {
render(<FormName />);
expect(screen.getByLabelText('Field 1 Label')).toBeInTheDocument();
expect(screen.getByLabelText('Field 2 Label')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /submit/i })).toBeInTheDocument();
});
it('validates required fields', async () => {
render(<FormName />);
const submitButton = screen.getByRole('button', { name: /submit/i });
fireEvent.click(submitButton);
await waitFor(() => {
expect(screen.getByText('Field 1 is required')).toBeInTheDocument();
});
});
it('submits form with valid data', async () => {
render(<FormName />);
const field1Input = screen.getByLabelText('Field 1 Label') as HTMLInputElement;
const field2Input = screen.getByLabelText('Field 2 Label') as HTMLInputElement;
const submitButton = screen.getByRole('button', { name: /submit/i });
fireEvent.change(field1Input, { target: { value: 'test value' } });
fireEvent.change(field2Input, { target: { value: '100' } });
fireEvent.click(submitButton);
await waitFor(() => {
expect(mockAddItem).toHaveBeenCalledWith(
expect.objectContaining({
field1: 'test value',
field2: '100',
})
);
});
});
it('clears form after successful submission', async () => {
render(<FormName />);
const field1Input = screen.getByLabelText('Field 1 Label') as HTMLInputElement;
const submitButton = screen.getByRole('button', { name: /submit/i });
fireEvent.change(field1Input, { target: { value: 'test' } });
fireEvent.click(submitButton);
await waitFor(() => {
expect(field1Input.value).toBe('');
});
});
it('disables form while loading', () => {
(useHealthStore as jest.Mock).mockReturnValue({
addItem: mockAddItem,
isLoading: true,
});
render(<FormName />);
const submitButton = screen.getByRole('button', { name: /submit/i });
expect(submitButton).toBeDisabled();
});
});
Create file: src/__tests__/lib/database/repositories/{EntityName}.test.ts
import { EntityRepository } from '@/lib/database/repositories/entityRepository';
import { getDatabase } from '@/lib/database/connection';
jest.mock('@/lib/database/connection');
describe('EntityRepository', () => {
let repo: EntityRepository;
let mockDb: any;
beforeEach(() => {
jest.clearAllMocks();
mockDb = {
prepare: jest.fn(),
};
(getDatabase as jest.Mock).mockReturnValue(mockDb);
repo = new EntityRepository();
});
it('adds entity correctly', () => {
const mockStmt = { run: jest.fn() };
mockDb.prepare.mockReturnValue(mockStmt);
const result = repo.addEntity({ field1: 'value1', field2: 'value2' });
expect(result).toHaveProperty('id');
expect(result).toHaveProperty('createdAt');
expect(result.field1).toBe('value1');
expect(mockStmt.run).toHaveBeenCalled();
});
it('gets entity by id', () => {
const mockStmt = { get: jest.fn() };
mockDb.prepare.mockReturnValue(mockStmt);
mockStmt.get.mockReturnValue({
id: '123',
field_1: 'value1',
field_2: '{"nested": "data"}',
});
const result = repo.getEntityById('123');
expect(result).toEqual(
expect.objectContaining({
id: '123',
field1: 'value1',
})
);
});
it('returns null for non-existent entity', () => {
const mockStmt = { get: jest.fn() };
mockDb.prepare.mockReturnValue(mockStmt);
mockStmt.get.mockReturnValue(undefined);
const result = repo.getEntityById('nonexistent');
expect(result).toBeNull();
});
it('throws error when updating non-existent entity', () => {
const mockStmt = { get: jest.fn() };
mockDb.prepare.mockReturnValue(mockStmt);
mockStmt.get.mockReturnValue(undefined);
expect(() => {
repo.updateEntity('nonexistent', {});
}).toThrow('Entity not found');
});
it('deletes entity correctly', () => {
const mockStmt = { run: jest.fn() };
mockDb.prepare.mockReturnValue(mockStmt);
repo.deleteEntity('123');
expect(mockStmt.run).toHaveBeenCalledWith('123');
});
});
Create file: src/__tests__/app/api/{resource}/route.test.ts
import { POST, DELETE } from '@/app/api/resource/route';
import { ResourceRepository } from '@/lib/database/repositories/resourceRepository';
jest.mock('@/lib/database/repositories/resourceRepository');
jest.mock('@/lib/database/repositories/dailySummaryRepository');
describe('Resource API Route', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('POST creates new resource', async () => {
const mockRepo = {
addResource: jest.fn().mockReturnValue({ id: '123', field: 'value' }),
};
(ResourceRepository as jest.Mock).mockImplementation(() => mockRepo);
const request = new Request('http://localhost:3000/api/resource', {
method: 'POST',
body: JSON.stringify({ field: 'value', date: '2024-01-15' }),
});
const response = await POST(request);
const data = await response.json();
expect(response.status).toBe(200);
expect(data).toEqual({ id: '123', field: 'value' });
});
it('DELETE removes resource', async () => {
const mockRepo = { deleteResource: jest.fn() };
(ResourceRepository as jest.Mock).mockImplementation(() => mockRepo);
const request = new Request('http://localhost:3000/api/resource?id=123', {
method: 'DELETE',
});
const response = await DELETE(request);
expect(response.status).toBe(200);
expect(mockRepo.deleteResource).toHaveBeenCalledWith('123');
});
it('DELETE returns 400 when id missing', async () => {
const request = new Request('http://localhost:3000/api/resource', {
method: 'DELETE',
});
const response = await DELETE(request);
expect(response.status).toBe(400);
});
});
src/__tests__/{SourceName}.test.ts(x)For components:
For repositories:
For API routes:
src/__tests__/{path}/{Name}.test.ts(x)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