动态模拟场景

在开发或展示你的工作时,你可能需要在运行时在不同的模拟场景之间切换。在演示中间转到源代码对你的观众来说不是一个好的体验。

¥When developing or presenting your work, you may need to switch between different mock scenarios on runtime. Going to the source code in the middle of a demo isn’t a good experience for your audience.

实现此目的的方法之一是声明一组场景(处理程序覆盖)并根据某些运行时条件(如查询参数)有条件地应用它们。

¥One of the ways to achieve this is to declare a set of scenarios (handler overrides) and conditionally apply them based on some runtime criteria, like query parameters.

// mocks/scenarios.js
import { http, HttpResponse } from 'msw'
 
export const scenarios = {
  success: [
    http.get('/user', () => {
      return HttpResponse.json({ name: 'John Maverick' })
    }),
  ],
  error: [
    http.get('/user', () => {
      return new HttpResponse(null, { status: 500 })
    }),
  ],
}
// mocks/browser.js
import { handlers } from './handlers'
import { scenarios } from './scenarios'
 
// Since the worker is registered on the client, you can read
// the page's query parameters before assigning request handlers.
const scenarioName = new URLSearchParams(window.location.search).get('scenario')
const runtimeScenarios = scenarios[scenarioName] || []
 
const worker = setupWorker(...runtimeScenarios, ...handlers)

请注意,处理程序的顺序很重要:最左边的处理程序在请求解析期间优先。

¥Note that the order of handlers is important: the left-most handlers take precedence during request resolution.

现在,如果你希望查看如果 GET /user 端点返回 500 Internal Server Error 响应,你的应用将如何表现,只需使用正确的 scenario 查询参数导航到你需要的页面:

¥Now, if you wish to see how your application behaves if the GET /user endpoint returns a 500 Internal Server Error response, simply navigate to the page you need with the proper scenario query parameter:

http://localhost:3000/dashboard?scenario=error