testing-with-api-mocks — ai-security testing-with-api-mocks, toolhive-studio, community, ai-security, ide skills, continue, copilot, developer-tools, mcp-client, model-context-protocol, Claude Code

v1.0.0

Об этом навыке

Идеально для агентов ИИ, которым необходимы эффективные тесты с автоматическими моками API, используя MSW Start here for all API mocking in tests. Covers auto-generation, fixtures, and when to use other skills. Required reading before creating, refactoring, or modifying any test involving API calls.

# Core Topics

stacklok stacklok
[116]
[13]
Updated: 3/3/2026

Killer-Skills Review

Decision support comes first. Repository text comes second.

Reference-Only Page Review Score: 7/11

This page remains useful for operators, but Killer-Skills treats it as reference material instead of a primary organic landing page.

Original recommendation layer Concrete use-case guidance Explicit limitations and caution
Review Score
7/11
Quality Score
49
Canonical Locale
en
Detected Body Locale
en

Идеально для агентов ИИ, которым необходимы эффективные тесты с автоматическими моками API, используя MSW Start here for all API mocking in tests. Covers auto-generation, fixtures, and when to use other skills. Required reading before creating, refactoring, or modifying any test involving API calls.

Зачем использовать этот навык

Позволяет агентам оптимизировать процессы разработки для серверов MCP и приложений ToolHive, создавая автоматически сгенерированные на основе схемы моки, используя MSW, что обеспечивает эффективное тестирование конечных точек API и сокращает время разработки

Подходит лучше всего

Идеально для агентов ИИ, которым необходимы эффективные тесты с автоматическими моками API, используя MSW

Реализуемые кейсы использования for testing-with-api-mocks

Автоматизировать генерацию моков API для тестов
Оптимизировать процессы разработки для серверов MCP
Эффективно тестировать приложения ToolHive с автоматически сгенерированными моками

! Безопасность и ограничения

  • Требуется настройка MSW (Mock Service Worker)
  • Ограничен до конечных точек API с существующей схемой

Why this page is reference-only

  • - Current locale does not satisfy the locale-governance contract.
  • - The underlying skill quality score is below the review floor.

Source Boundary

The section below is supporting source material from the upstream repository. Use the Killer-Skills review above as the primary decision layer.

Labs Demo

Browser Sandbox Environment

⚡️ Ready to unleash?

Experience this Agent in a zero-setup browser environment powered by WebContainers. No installation required.

Boot Container Sandbox

FAQ & Installation Steps

These questions and steps mirror the structured data on this page for better search understanding.

? Frequently Asked Questions

What is testing-with-api-mocks?

Идеально для агентов ИИ, которым необходимы эффективные тесты с автоматическими моками API, используя MSW Start here for all API mocking in tests. Covers auto-generation, fixtures, and when to use other skills. Required reading before creating, refactoring, or modifying any test involving API calls.

How do I install testing-with-api-mocks?

Run the command: npx killer-skills add stacklok/toolhive-studio. It works with Cursor, Windsurf, VS Code, Claude Code, and 19+ other IDEs.

What are the use cases for testing-with-api-mocks?

Key use cases include: Автоматизировать генерацию моков API для тестов, Оптимизировать процессы разработки для серверов MCP, Эффективно тестировать приложения ToolHive с автоматически сгенерированными моками.

Which IDEs are compatible with testing-with-api-mocks?

This skill is compatible with Cursor, Windsurf, VS Code, Trae, Claude Code, OpenClaw, Aider, Codex, OpenCode, Goose, Cline, Roo Code, Kiro, Augment Code, Continue, GitHub Copilot, Sourcegraph Cody, and Amazon Q Developer. Use the Killer-Skills CLI for universal one-command installation.

Are there any limitations for testing-with-api-mocks?

Требуется настройка MSW (Mock Service Worker). Ограничен до конечных точек API с существующей схемой.

How To Install

  1. 1. Open your terminal

    Open the terminal or command line in your project directory.

  2. 2. Run the install command

    Run: npx killer-skills add stacklok/toolhive-studio. The CLI will automatically detect your IDE or AI agent and configure the skill.

  3. 3. Start using the skill

    The skill is now active. Your AI agent can use testing-with-api-mocks immediately in the current project.

! Reference-Only Mode

This page remains useful for installation and reference, but Killer-Skills no longer treats it as a primary indexable landing page. Read the review above before relying on the upstream repository instructions.

Imported Repository Instructions

The section below is supporting source material from the upstream repository. Use the Killer-Skills review above as the primary decision layer.

Supporting Evidence

testing-with-api-mocks

Install testing-with-api-mocks, an AI agent skill for AI agent workflows and automation. Works with Claude Code, Cursor, and Windsurf with one-command setup.

SKILL.md
Readonly
Imported Repository Instructions
The section below is supporting source material from the upstream repository. Use the Killer-Skills review above as the primary decision layer.
Supporting Evidence

Testing with API Mocks

This is the starting point for all API mocking in tests. Read this skill first before working on any test that involves API calls.

This project uses MSW (Mock Service Worker) with auto-generated schema-based mocks. When writing tests for code that calls API endpoints, mocks are created automatically.

How It Works

  1. Run a test that triggers an API call (e.g., a component that fetches data)
  2. Mock auto-generates if no fixture exists for that endpoint
  3. Fixture saved to renderer/src/common/mocks/fixtures/<endpoint>/<method>.ts
  4. Subsequent runs use the saved fixture

No manual mock setup is required for basic tests.

Fixture Location

Fixtures are organized by endpoint path and HTTP method:

renderer/src/common/mocks/fixtures/
├── groups/
│   ├── get.ts          # GET /api/v1beta/groups
│   └── post.ts         # POST /api/v1beta/groups
├── workloads/
│   └── get.ts          # GET /api/v1beta/workloads
├── workloads_name/
│   └── get.ts          # GET /api/v1beta/workloads/:name
└── ...

Path parameters like :name become _name in the directory name.

Fixture Structure

Generated fixtures use the AutoAPIMock wrapper with types from the OpenAPI schema:

typescript
1// renderer/src/common/mocks/fixtures/groups/get.ts 2import type { 3 GetApiV1BetaGroupsResponse, 4 GetApiV1BetaGroupsData, 5} from '@common/api/generated/types.gen' 6import { AutoAPIMock } from '@mocks' 7 8export const mockedGetApiV1BetaGroups = AutoAPIMock< 9 GetApiV1BetaGroupsResponse, 10 GetApiV1BetaGroupsData 11>({ 12 groups: [ 13 { name: 'default', registered_clients: ['client-a'] }, 14 { name: 'research', registered_clients: ['client-b'] }, 15 ], 16})

The second type parameter (*Data) provides typed access to request parameters (query, path, body) for conditional overrides.

Naming Convention

Export names follow the pattern: mocked + HTTP method + endpoint path in PascalCase.

  • GET /api/v1beta/groupsmockedGetApiV1BetaGroups
  • POST /api/v1beta/workloadsmockedPostApiV1BetaWorkloads
  • GET /api/v1beta/workloads/:namemockedGetApiV1BetaWorkloadsByName

Writing a Basic Test

For most tests, just render the component and the mock handles the rest:

typescript
1import { render, screen, waitFor } from '@testing-library/react' 2 3it('displays groups from the API', async () => { 4 render(<GroupsList />) 5 6 await waitFor(() => { 7 expect(screen.getByText('default')).toBeVisible() 8 }) 9})

The auto-generated mock provides realistic fake data based on the OpenAPI schema.

Customizing Fixture Data

If the auto-generated data doesn't suit your test, edit the fixture file directly:

typescript
1// renderer/src/common/mocks/fixtures/groups/get.ts 2export const mockedGetApiV1BetaGroups = AutoAPIMock< 3 GetApiV1BetaGroupsResponse, 4 GetApiV1BetaGroupsData 5>({ 6 groups: [ 7 { name: 'production', registered_clients: ['claude-code'] }, // Custom data 8 { name: 'staging', registered_clients: [] }, 9 ], 10})

This becomes the new default for all tests using this endpoint.

Regenerating a Fixture

To regenerate a fixture with fresh schema-based data:

  1. Delete the fixture file
  2. Run a test that calls that endpoint
  3. New fixture auto-generates
bash
1rm renderer/src/common/mocks/fixtures/groups/get.ts 2pnpm test -- --run <test-file>

Key Imports

typescript
1// Types for API responses and request parameters 2import type { 3 GetApiV1BetaGroupsResponse, 4 GetApiV1BetaGroupsData, 5} from '@common/api/generated/types.gen' 6 7// AutoAPIMock wrapper 8import { AutoAPIMock } from '@mocks' 9 10// Fixture mocks (for test-scoped overrides, see: testing-api-overrides skill) 11import { mockedGetApiV1BetaGroups } from '@mocks/fixtures/groups/get'

204 No Content Endpoints

For endpoints that return 204, create a minimal AutoAPIMock fixture and override the handler in each test:

typescript
1// renderer/src/common/mocks/fixtures/health/get.ts 2import type { 3 GetHealthResponse, 4 GetHealthData, 5} from '@common/api/generated/types.gen' 6import { AutoAPIMock } from '@mocks' 7 8export const mockedGetHealth = AutoAPIMock<GetHealthResponse, GetHealthData>( 9 '' as unknown as GetHealthResponse 10)

Then in tests, use .overrideHandler() to return the appropriate response:

typescript
1import { mockedGetHealth } from '@mocks/fixtures/health/get' 2import { HttpResponse } from 'msw' 3 4it('navigates on health check success', async () => { 5 mockedGetHealth.overrideHandler(() => new HttpResponse(null, { status: 204 })) 6 // ... 7}) 8 9it('handles health check failure', async () => { 10 mockedGetHealth.overrideHandler(() => HttpResponse.error()) 11 // ... 12})

Custom Mocks (Text/Plain Endpoints)

Custom mocks are only needed for text/plain endpoints. The only current example is the logs endpoint:

typescript
1// renderer/src/common/mocks/customHandlers/index.ts 2export const customHandlers = [ 3 http.get(mswEndpoint('/api/v1beta/workloads/:name/logs'), ({ params }) => { 4 const { name } = params 5 const logs = getMockLogs(name as string) 6 return new HttpResponse(logs, { status: 200 }) 7 }), 8]

To override the logs response in tests, use the exported getMockLogs mock:

typescript
1import { getMockLogs } from '@/common/mocks/customHandlers' 2 3getMockLogs.mockReturnValueOnce('Custom log content for this test')
  • testing-api-overrides - Test-scoped overrides and conditional responses for testing filters/params
  • testing-api-assertions - Verifying API calls for mutations (create/update/delete)

Связанные навыки

Looking for an alternative to testing-with-api-mocks or another community skill for your workflow? Explore these related open-source skills.

Показать все

openclaw-release-maintainer

Logo of openclaw
openclaw

Your own personal AI assistant. Any OS. Any Platform. The lobster way. 🦞

widget-generator

Logo of f
f

Создание настраиваемых плагинов виджетов для системы ленты новостей prompts.chat

flags

Logo of vercel
vercel

Фреймворк React

138.4k
0
Браузер

pr-review

Logo of pytorch
pytorch

Tensors and Dynamic neural networks in Python with strong GPU acceleration

98.6k
0
Разработчик