Mocking HTTP
拦截和模拟 HTTP 请求。
Mock Service Worker 支持通过库提供的 http
命名空间拦截和模拟 HTTP 请求:
¥Mock Service Worker supports the interception and mocking of HTTP requests via the http
namespace provided by the library:
import { http } from 'msw'
http
API reference for the `http` namespace.
本页将概述模拟体验以及在项目中使用 MSW 的一些好处。请参阅本节中的其他页面,了解有关请求拦截、响应模拟、特定方案和最佳实践的更多详细信息。
¥This page will give you an overview of the mocking experience and some of the benefits of using MSW in your project. Please refer to the additional pages in this section for more details about the request interception, response mocking, specific recipes, and best practices.
Web 标准
¥Web standards
我们遵循 Web 标准。这就是为什么在使用 MSW 时,你将使用 Fetch API 来处理拦截的请求并构建模拟响应(即使它们不是用 fetch()
生成的)。不可避免地,在解决手头的具体任务时,你将更好地理解 Web 基础知识。
¥We believe in web standards. That is why when using MSW you will be working with the Fetch API to handle intercepted requests and construct mocked responses (even if they weren’t made with fetch()
). Inevitably, you will become better at understanding the web fundamentals while solving the exact tasks you have at hand.
如果你熟悉 Web 上的请求和响应,那么你就知道如何使用 MSW。
¥If you are familiar with requests and responses on the web, you know how to use MSW.
优点
¥Benefits
以下是使用 MSW 模拟 HTTP API 的一些好处:
¥Here are some of the benefits of using MSW for mocking HTTP APIs:
-
与客户端无关。该库会拦截任何 HTTP 请求,无论请求客户端是什么。今天使用普通的
fetch()
,明天使用任何第三方客户端 - 你的模拟代码保持不变。¥Client-agnostic. The library intercepts any HTTP requests, regardless of the request client. Use plain
fetch()
today, or any third-party client tomorrow—your mocks remain the same. -
无缝。对测试代码进行零更改。请求相同的生产资源,使用 MSW 在网络级别拦截它们,并以你需要的任何方式处理它们。
¥Seamless. Make zero changes to the tested code. Request the same production resources, intercept them on the network level with MSW, and handle them in any way you need.
-
可重用。将相同的模拟用于不同的目的:本地开发、自动化测试、调试和展示你的应用。
¥Reusable. Use the same mocks for different purposes: local development, automated testing, debugging, and showcasing your app.
-
类型安全。注释路径参数、请求和响应主体类型,以免模拟结果再次过期。
¥Type-safe. Annotate path parameters, request and response body types to never have out-of-date mocks again.
后续步骤
¥Next steps
以下部分将指导你了解有关拦截和模拟 HTTP 请求的所有知识:
¥The following sections will guide you through everything you need to know about intercepting and mocking HTTP requests: