保持模拟同步

你编写模拟来描述及时固定的服务器行为。但随着时间的推移,这种行为可能会发生变化,可能导致你的模拟过时。

¥You write mocks to describe a server behavior fixed in time. But as time goes on, that behavior may change, potentially rendering your mocks obsolete.

有多种方法可以使你的模拟定义与实际后端保持同步。

¥There are multiple ways to keep your mock definitions in-sync with the actual backend.

使用规范(推荐)

¥Use specification (Recommended)

建议依赖后端和前端都可以用作事实来源的规范文件。将后端运行时视为事实很容易出现问题,因为后端可能会引入违反预期规范的错误运行时行为。

¥It’s recommended to rely on a specification file that both backend and frontend can use as the source of truth. Treating the backend runtime as the truth is prone to issues as the backend may introduce faulty runtime behavior that violates the intended specification.

OpenAPI (Swagger)

如果你有 OpenAPI 规范文件,请考虑使用 msw-auto-mock 包从中生成请求处理程序。

¥If you have an OpenAPI specification file, consider using the msw-auto-mock package to generate request handlers from it.

GraphQL 模式

¥GraphQL schema

对于 GraphQL 服务器,请考虑使用 GraphQL 代码生成器 及其 typescript-msw 插件自动从 GraphQL 查询创建请求处理程序。

¥In the case of a GraphQL server, consider using GraphQL Code Generator and its typescript-msw plugin to automatically create request handlers from your GraphQL queries.

使用网络快照

¥Use network snapshots

如果没有可用的 API 规范,你可以在浏览器中记录网络行为并将其存储在 *.har 文件中。然后,它将成为你可以用来生成处理程序的固定事实来源。

¥In the case when there is no API specification available, you can record network behavior in the browser and store it in a *.har file. Then, it becomes a fixed source of truth you can use to generate handlers from.

在下面的例子中,我们将使用社区编写的 msw-webarchive 包在运行时从 HAR 文件生成请求处理程序。

¥In the example below we’are going to use a community-authored msw-webarchive package to generate request handlers from an HAR file on runtime.

// mocks/browser.js
import { setupWorker } from 'msw'
import { setRequestHandlersByWebarchive } from '@tapico/webarchive'
import * as snapshot from './snapshort.har'
 
export const worker = setupWorker()
 
// Augment the worker with request handlers
// generated from the given network snapshot
setRequestHandlersByWebarchive(worker, snapshot)

自动化流程

¥Automate the process

无论你选择哪种方法,请考虑通过配置 CI 来定期更新规范/网络快照来自动化该过程。这样我们就可以确保模拟随着时间的推移保持相关性。

¥Regardless of the approach you chose, consider automating the process by configuring your CI to regularly update the specification/network snapshots. That way we can ensure that the mocks remain relevant over time.