mocking-assistant
Creates stable mocks for APIs, services, and UI components using MSW (Mock Service Worker), fixture conventions, and example patterns. Use for "API mocking", "MSW", "test mocks", or "service mocking".
What this skill does
# Mocking Assistant
Create reliable mocks for APIs and services in tests.
## MSW API Mocking
```typescript
// mocks/handlers.ts
import { http, HttpResponse } from "msw";
export const handlers = [
// GET endpoint
http.get("/api/users/:id", ({ params }) => {
const { id } = params;
return HttpResponse.json({
id,
name: "John Doe",
email: "[email protected]",
});
}),
// POST endpoint
http.post("/api/users", async ({ request }) => {
const body = await request.json();
return HttpResponse.json(
{
id: Math.random().toString(),
...body,
createdAt: new Date().toISOString(),
},
{ status: 201 }
);
}),
// Error response
http.get("/api/products/:id", ({ params }) => {
const { id } = params;
if (id === "404") {
return HttpResponse.json({ error: "Product not found" }, { status: 404 });
}
return HttpResponse.json({
id,
name: "MacBook Pro",
price: 2499.99,
});
}),
// Delayed response
http.get("/api/slow-endpoint", async () => {
await delay(2000);
return HttpResponse.json({ data: "Slow response" });
}),
];
```
## MSW Setup
```typescript
// mocks/server.ts
import { setupServer } from "msw/node";
import { handlers } from "./handlers";
export const server = setupServer(...handlers);
// tests/setup.ts
import { beforeAll, afterEach, afterAll } from "vitest";
import { server } from "../mocks/server";
beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
```
## Fixture Conventions
```typescript
// mocks/fixtures/users.ts
export const userFixtures = {
admin: {
id: "1",
email: "[email protected]",
name: "Admin User",
role: "ADMIN",
},
customer: {
id: "2",
email: "[email protected]",
name: "Customer User",
role: "USER",
},
guest: {
id: "3",
email: "[email protected]",
name: "Guest User",
role: "GUEST",
},
};
// mocks/fixtures/products.ts
export const productFixtures = {
laptop: {
id: "100",
name: "MacBook Pro",
price: 2499.99,
stock: 10,
category: "Electronics",
},
phone: {
id: "101",
name: "iPhone 15",
price: 999.99,
stock: 50,
category: "Electronics",
},
outOfStock: {
id: "102",
name: "Sold Out Item",
price: 499.99,
stock: 0,
category: "Electronics",
},
};
// Usage in handlers
http.get("/api/users/:id", ({ params }) => {
const user = Object.values(userFixtures).find((u) => u.id === params.id);
if (!user) {
return HttpResponse.json({ error: "User not found" }, { status: 404 });
}
return HttpResponse.json(user);
});
```
## Test-Specific Mocks
```typescript
// tests/components/UserProfile.test.tsx
import { server } from "../mocks/server";
import { http, HttpResponse } from "msw";
test("should display user profile", async () => {
// Override handler for this test
server.use(
http.get("/api/users/123", () => {
return HttpResponse.json({
id: "123",
name: "Test User",
email: "[email protected]",
});
})
);
render(<UserProfile userId="123" />);
await waitFor(() => {
expect(screen.getByText("Test User")).toBeInTheDocument();
});
});
test("should handle API error", async () => {
// Mock error response
server.use(
http.get("/api/users/123", () => {
return HttpResponse.json({ error: "Server error" }, { status: 500 });
})
);
render(<UserProfile userId="123" />);
await waitFor(() => {
expect(screen.getByText("Failed to load user")).toBeInTheDocument();
});
});
```
## Service Mocking
```typescript
// src/services/paymentService.ts
export interface PaymentService {
processPayment(amount: number, cardToken: string): Promise<PaymentResult>;
refund(transactionId: string): Promise<void>;
}
// mocks/services/mockPaymentService.ts
export class MockPaymentService implements PaymentService {
async processPayment(
amount: number,
cardToken: string
): Promise<PaymentResult> {
// Simulate successful payment
if (cardToken.startsWith("tok_success")) {
return {
transactionId: "txn_" + Math.random().toString(36),
status: "success",
amount,
};
}
// Simulate failed payment
if (cardToken.startsWith("tok_fail")) {
throw new Error("Payment failed");
}
// Simulate slow payment
await new Promise((resolve) => setTimeout(resolve, 2000));
return {
transactionId: "txn_" + Math.random().toString(36),
status: "success",
amount,
};
}
async refund(transactionId: string): Promise<void> {
// Mock refund
console.log(`Refunding transaction: ${transactionId}`);
}
}
// tests/checkout.test.ts
const mockPaymentService = new MockPaymentService();
test("should process payment successfully", async () => {
const result = await mockPaymentService.processPayment(
100,
"tok_success_123"
);
expect(result.status).toBe("success");
expect(result.transactionId).toBeDefined();
});
```
## Function Mocking with Vitest
```typescript
// src/utils/analytics.ts
export const trackEvent = (event: string, data: any) => {
// Send to analytics service
};
// tests/component.test.ts
import { vi } from "vitest";
import * as analytics from "@/utils/analytics";
test("should track button click", () => {
// Mock function
const trackEventSpy = vi.spyOn(analytics, "trackEvent");
render(<Button onClick={handleClick} />);
fireEvent.click(screen.getByRole("button"));
expect(trackEventSpy).toHaveBeenCalledWith("button_click", {
buttonId: "submit",
});
});
```
## Date/Time Mocking
```typescript
// tests/date-sensitive.test.ts
import { vi } from "vitest";
test("should show correct greeting based on time", () => {
// Mock date to morning
vi.setSystemTime(new Date("2024-01-01 09:00:00"));
render(<Greeting />);
expect(screen.getByText("Good morning!")).toBeInTheDocument();
// Mock date to evening
vi.setSystemTime(new Date("2024-01-01 19:00:00"));
render(<Greeting />);
expect(screen.getByText("Good evening!")).toBeInTheDocument();
// Restore real time
vi.useRealTimers();
});
```
## Module Mocking
```typescript
// src/lib/database.ts
export const db = {
user: {
findById: (id: string) => {
// Real database query
},
},
};
// tests/mocks/database.ts
export const mockDb = {
user: {
findById: vi.fn((id: string) => ({
id,
name: "Mock User",
email: "[email protected]",
})),
},
};
// tests/userService.test.ts
vi.mock("@/lib/database", () => ({
db: mockDb,
}));
test("should fetch user from database", async () => {
const user = await userService.getUser("123");
expect(mockDb.user.findById).toHaveBeenCalledWith("123");
expect(user.name).toBe("Mock User");
});
```
## GraphQL Mocking
```typescript
// mocks/graphql-handlers.ts
import { graphql, HttpResponse } from "msw";
export const graphqlHandlers = [
graphql.query("GetUser", ({ variables }) => {
return HttpResponse.json({
data: {
user: {
id: variables.id,
name: "John Doe",
email: "[email protected]",
},
},
});
}),
graphql.mutation("CreateUser", ({ variables }) => {
return HttpResponse.json({
data: {
createUser: {
id: Math.random().toString(),
...variables.input,
},
},
});
}),
];
```
## Best Practices
1. **Use MSW for HTTP**: More realistic than mocking fetch
2. **Centralize fixtures**: Single source of truth
3. **Test-specific overrides**: Override defaults per test
4. **Mock at boundaries**: Services, APIs, not internals
5. **Realistic data**: Fixtures should match production
6. **Error scenarios**: Test failure cases
7. **Timing control**: Mock delays for loading states
## Output Checklist
- [ ] MSW handlers created
- [ ] Fixture conveRelated in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.