跳到正文
cccskills
免费在 GitHub 公开

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".

中文简介正在准备中。当前显示原文说明。

查看安装方法

包含的文件(1)

  • SKILL.md8.3 KB

SKILL.md(原文)

安装前可以查看交给 AI 代理的指令内容。

Mocking Assistant

Create reliable mocks for APIs and services in tests.

MSW API Mocking

// 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: "john@example.com",
    });
  }),

  // 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

// 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

// mocks/fixtures/users.ts
export const userFixtures = {
  admin: {
    id: "1",
    email: "admin@example.com",
    name: "Admin User",
    role: "ADMIN",
  },
  customer: {
    id: "2",
    email: "customer@example.com",
    name: "Customer User",
    role: "USER",
  },
  guest: {
    id: "3",
    email: "guest@example.com",
    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

// 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: "test@example.com",
      });
    })
  );

  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

// 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

// 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

// 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

// 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: "mock@example.com",
    })),
  },
};

// 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

// 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: "john@example.com",
        },
      },
    });
  }),

  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 conventions established
  • Common fixtures defined
  • Test-specific mock overrides
  • Service mocks implemented
  • Function spies used appropriately
  • Date/time mocking when needed
  • Error scenarios mocked
  • GraphQL mocks (if applicable)
  • Documentation for mock usage

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

Audits and implements web accessibility (a11y) following WCAG 2.1 guidelines with ARIA patterns, keyboard navigation, screen reader support, and contrast checking. Use when users request "accessibility audit", "a11y review", "WCAG compliance", "screen reader support", or "keyboard navigation".

中文简介正在准备中。当前显示原文说明。

sathishssj3/Stereix-Engine22026年10月4日 更新

Creates Architecture Decision Records documenting key technical decisions with context, alternatives considered, tradeoffs, consequences, and decision owners. Use when documenting "architecture decisions", "technical choices", "design decisions", or "ADRs".

中文简介正在准备中。当前显示原文说明。

sathishssj3/Stereix-Engine22026年10月4日 更新

Designs multi-step agent workflows with tool usage, retry logic, state management, and budget controls. Provides orchestration diagrams, tool execution order, fallback strategies, and cost limits. Use for "AI agents", "agentic workflows", "multi-step AI", or "autonomous systems".

中文简介正在准备中。当前显示原文说明。

sathishssj3/Stereix-Engine22026年10月4日 更新

MUST USE when user wants to 调研/research/搜索/search/查/找/look up anything on the internet — e.g. 全网调研 X / 帮我调研一下 X / 查一下 X / 搜搜 X / 看看大家怎么评价 X / X 上有什么讨论 / research this topic。 Also MUST USE when user mentions any platform or shares any URL/链接: 小红书/xiaohongshu/xhs, Twitter/推特/X, B站/bilibili, Reddit, Facebook, Instagram, V2EX, LinkedIn/领英/招聘/求职/jobs, YouTube, GitHub code search, 小宇宙播客, 雪球/股票行情, RSS feeds, or any web URL. 15 platforms, multi-backend routing (OpenCLI / per-platform CLIs / APIs). Zero config for 6 channels. Run `agent-reach doctor --json` to see which backend serves each platform right now. NOT for: 写报告/数据分析/翻译等内容加工(本 skill 只负责从互联网获取内容); 发帖/评论/点赞等写操作;已有专门 skill 的平台(先用专门 skill)。 【路由方式】SKILL.md 包含路由表和常用命令,复杂场景需按需阅读对应分类的 references/*.md。 分类:search / social (小红书/推特/B站/V2EX/Reddit/Facebook/Instagram) / career(LinkedIn) / dev(github) / web(网页/文章/RSS) / video(YouTube/B站/播客) / finance(雪球/股票)。

中文简介正在准备中。当前显示原文说明。

sathishssj3/Stereix-Engine22026年10月4日 更新

Orchestrates multi-agent AI systems with task delegation, agent communication, shared memory, and workflow coordination. Use when users request "multi-agent system", "agent orchestration", "AI agents", "agent coordination", or "autonomous agents".

中文简介正在准备中。当前显示原文说明。

sathishssj3/Stereix-Engine22026年10月4日 更新

Creates SLO-based alerts and operational dashboards with key charts, alert thresholds, and runbook links. Use for "alerting", "dashboards", "SLO", or "monitoring".

中文简介正在准备中。当前显示原文说明。

sathishssj3/Stereix-Engine22026年10月4日 更新

查看 sathishssj3 的全部技能

报告此技能的问题