msw

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

MSW Best Practices

MSW 最佳实践

Comprehensive API mocking guide for MSW v2 applications, designed for AI agents and LLMs. Contains 45 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
为AI Agent和LLM打造的MSW v2应用全面API模拟指南。包含8个类别共45条规则,按影响优先级排序,用于指导自动化重构和代码生成。

When to Apply

适用场景

Reference these guidelines when:
  • Setting up MSW for testing or development
  • Writing or organizing request handlers
  • Configuring test environments with MSW
  • Mocking REST or GraphQL APIs
  • Debugging handler matching issues
  • Testing error states and edge cases
参考以下指南的场景:
  • 为测试或开发设置MSW
  • 编写或整理请求处理程序
  • 使用MSW配置测试环境
  • 模拟REST或GraphQL API
  • 调试处理程序匹配问题
  • 测试错误状态和边缘情况

Rule Categories by Priority

按优先级划分的规则类别

PriorityCategoryImpactPrefix
1Setup & InitializationCRITICAL
setup-
2Handler ArchitectureCRITICAL
handler-
3Test IntegrationHIGH
test-
4Response PatternsHIGH
response-
5Request MatchingMEDIUM-HIGH
match-
6GraphQL MockingMEDIUM
graphql-
7Advanced PatternsMEDIUM
advanced-
8Debugging & PerformanceLOW
debug-
优先级类别影响程度前缀
1安装与初始化关键
setup-
2处理程序架构关键
handler-
3测试集成
test-
4响应模式
response-
5请求匹配中高
match-
6GraphQL模拟
graphql-
7高级模式
advanced-
8调试与性能
debug-

Quick Reference

快速参考

1. Setup & Initialization (CRITICAL)

1. 安装与初始化(关键)

  • setup-server-node-entrypoint
    - Use correct entrypoint for Node.js (msw/node)
  • setup-lifecycle-hooks
    - Configure server lifecycle in test setup
  • setup-worker-script-commit
    - Commit worker script to version control
  • setup-node-version
    - Require Node.js 18+ for MSW v2
  • setup-unhandled-requests
    - Configure unhandled request behavior
  • setup-typescript-config
    - Configure TypeScript for MSW v2
  • setup-server-node-entrypoint
    - 为Node.js使用正确的入口(msw/node)
  • setup-lifecycle-hooks
    - 在测试设置中配置服务器生命周期
  • setup-worker-script-commit
    - 将Worker脚本提交到版本控制
  • setup-node-version
    - MSW v2要求Node.js 18及以上版本
  • setup-unhandled-requests
    - 配置未处理请求的行为
  • setup-typescript-config
    - 为MSW v2配置TypeScript

2. Handler Architecture (CRITICAL)

2. 处理程序架构(关键)

  • handler-happy-path-first
    - Define happy path handlers as baseline
  • handler-domain-grouping
    - Group handlers by domain
  • handler-absolute-urls
    - Use absolute URLs in handlers
  • handler-shared-resolvers
    - Extract shared response logic into resolvers
  • handler-v2-response-syntax
    - Use MSW v2 response syntax
  • handler-request-body-parsing
    - Explicitly parse request bodies
  • handler-resolver-argument
    - Destructure resolver arguments correctly
  • handler-reusability-environments
    - Share handlers across environments
  • handler-happy-path-first
    - 将正常流程处理程序定义为基准
  • handler-domain-grouping
    - 按域名分组处理程序
  • handler-absolute-urls
    - 在处理程序中使用绝对URL
  • handler-shared-resolvers
    - 将共享响应逻辑提取到解析器中
  • handler-v2-response-syntax
    - 使用MSW v2响应语法
  • handler-request-body-parsing
    - 显式解析请求体
  • handler-resolver-argument
    - 正确解构解析器参数
  • handler-reusability-environments
    - 在多环境间共享处理程序

3. Test Integration (HIGH)

3. 测试集成(高)

  • test-reset-handlers
    - Reset handlers after each test
  • test-avoid-request-assertions
    - Avoid direct request assertions
  • test-concurrent-boundary
    - Use server.boundary() for concurrent tests
  • test-fake-timers-config
    - Configure fake timers to preserve queueMicrotask
  • test-async-utilities
    - Use async testing utilities for mock responses
  • test-clear-request-cache
    - Clear request library caches between tests
  • test-jsdom-environment
    - Use correct JSDOM environment for Jest
  • test-reset-handlers
    - 每次测试后重置处理程序
  • test-avoid-request-assertions
    - 避免直接断言请求
  • test-concurrent-boundary
    - 对并发测试使用server.boundary()
  • test-fake-timers-config
    - 配置假计时器以保留queueMicrotask
  • test-async-utilities
    - 对模拟响应使用异步测试工具
  • test-clear-request-cache
    - 在测试间清除请求库缓存
  • test-jsdom-environment
    - 为Jest使用正确的JSDOM环境

4. Response Patterns (HIGH)

4. 响应模式(高)

  • response-http-response-helpers
    - Use HttpResponse static methods
  • response-delay-realistic
    - Add realistic response delays
  • response-error-simulation
    - Simulate error responses correctly
  • response-one-time-handlers
    - Use one-time handlers for sequential scenarios
  • response-custom-headers
    - Set response headers correctly
  • response-streaming
    - Mock streaming responses with ReadableStream
  • response-http-response-helpers
    - 使用HttpResponse静态方法
  • response-delay-realistic
    - 添加真实的响应延迟
  • response-error-simulation
    - 正确模拟错误响应
  • response-one-time-handlers
    - 为顺序场景使用一次性处理程序
  • response-custom-headers
    - 正确设置响应头
  • response-streaming
    - 使用ReadableStream模拟流式响应

5. Request Matching (MEDIUM-HIGH)

5. 请求匹配(中高)

  • match-url-patterns
    - Use URL path parameters correctly
  • match-query-params
    - Access query parameters from request URL
  • match-custom-predicate
    - Use custom predicates for complex matching
  • match-http-methods
    - Match HTTP methods explicitly
  • match-handler-order
    - Order handlers from specific to general
  • match-url-patterns
    - 正确使用URL路径参数
  • match-query-params
    - 从请求URL中获取查询参数
  • match-custom-predicate
    - 对复杂匹配使用自定义断言
  • match-http-methods
    - 显式匹配HTTP方法
  • match-handler-order
    - 按从具体到通用的顺序排列处理程序

6. GraphQL Mocking (MEDIUM)

6. GraphQL模拟(中)

  • graphql-operation-handlers
    - Use operation name for GraphQL matching
  • graphql-error-responses
    - Return GraphQL errors in correct format
  • graphql-batched-queries
    - Handle batched GraphQL queries
  • graphql-variables-access
    - Access GraphQL variables correctly
  • graphql-operation-handlers
    - 使用操作名称进行GraphQL匹配
  • graphql-error-responses
    - 以正确格式返回GraphQL错误
  • graphql-batched-queries
    - 处理批量GraphQL查询
  • graphql-variables-access
    - 正确获取GraphQL变量

7. Advanced Patterns (MEDIUM)

7. 高级模式(中)

  • advanced-bypass-requests
    - Use bypass() for passthrough requests
  • advanced-cookies-auth
    - Handle cookies and authentication
  • advanced-dynamic-scenarios
    - Implement dynamic mock scenarios
  • advanced-vitest-browser
    - Configure MSW for Vitest browser mode
  • advanced-file-uploads
    - Mock file upload endpoints
  • advanced-bypass-requests
    - 对直通请求使用bypass()
  • advanced-cookies-auth
    - 处理Cookie与身份验证
  • advanced-dynamic-scenarios
    - 实现动态模拟场景
  • advanced-vitest-browser
    - 为Vitest浏览器模式配置MSW
  • advanced-file-uploads
    - 模拟文件上传端点

8. Debugging & Performance (LOW)

8. 调试与性能(低)

  • debug-lifecycle-events
    - Use lifecycle events for debugging
  • debug-verify-interception
    - Verify request interception is working
  • debug-common-issues
    - Know common MSW issues and fixes
  • debug-request-logging
    - Log request details for debugging
  • debug-lifecycle-events
    - 使用生命周期事件进行调试
  • debug-verify-interception
    - 验证请求拦截是否正常工作
  • debug-common-issues
    - 了解MSW常见问题及修复方法
  • debug-request-logging
    - 记录请求详情用于调试

How to Use

使用方法

Read individual reference files for detailed explanations and code examples:
  • Section definitions - Category structure and impact levels
  • Rule template - Template for adding new rules
  • Individual rules:
    references/{prefix}-{slug}.md
阅读各参考文件获取详细说明和代码示例:
  • 章节定义 - 类别结构和影响程度
  • 规则模板 - 添加新规则的模板
  • 单个规则:
    references/{prefix}-{slug}.md

Related Skills

相关技能

  • For generating MSW mocks from OpenAPI, see
    orval
    skill
  • For consuming mocked APIs, see
    tanstack-query
    skill
  • For test methodology, see
    test-vitest
    or
    test-tdd
    skills
  • 如需从OpenAPI生成MSW模拟,请查看
    orval
    技能
  • 如需使用模拟API,请查看
    tanstack-query
    技能
  • 如需了解测试方法论,请查看
    test-vitest
    test-tdd
    技能

Full Compiled Document

完整编译文档

For the complete guide with all rules expanded:
AGENTS.md
如需包含所有扩展规则的完整指南,请查看:
AGENTS.md