浏览器集成
在浏览器中设置 Mock Service Worker。
在浏览器中,MSW 通过注册负责网络级别请求拦截的 Service Worker 来工作。
¥In the browser, MSW works by registering a Service Worker responsible for request interception on the network level.
尽管 Service Workers 旨在通过 HTTPS 提供服务,但浏览器允许在 localhost 上开发时在 HTTP 上注册 Workers。如果你需要本地 HTTPS 开发,请参阅 此秘诀。
¥Although Service Workers are meant to be served via HTTPS, browsers allow
registering workers on HTTP while developing on localhost. If you need a
local HTTPS development, see this recipe.
生成 worker 脚本
¥Generating the worker script
如果你的应用注册了 Service Worker,则必须托管并为其提供服务。库 CLI 为你提供了 init 命令,以便快速将 ./mockServiceWorker.js 工作脚本复制到应用的公共目录中。
¥If your application registers a Service Worker it must host and serve it. The library CLI provides you with the init command to quickly copy the ./mockServiceWorker.js worker script into your application’s public directory.
npx msw init <PUBLIC_DIR> --save了解有关
initCLI 命令 的更多信息。¥Learn more about the
initCLI command.
复制后,在浏览器中导航到应用的 /mockServiceWorker.js URL(例如,如果你的应用在 http://localhost:3000 上运行,请转到 http://localhost:3000/mockServiceWorker.js 路由)。你应该看到工作脚本内容。如果你看到 404 或 MIME 类型错误,请确保在运行 init 命令时指定了正确的 PUBLIC_DIR,并调整了应用的任何潜在配置,这些配置可能会影响提供静态文件。
¥Once copied, navigate to the /mockServiceWorker.js URL of your application in your browser (e.g. if your application is running on http://localhost:3000, go to the http://localhost:3000/mockServiceWorker.js route). You should see the worker script contents. If you see a 404 or a MIME type error, make sure you are specifying the correct PUBLIC_DIR when running the init command, and that you adjust any potential configuration of your application that would affect serving static files.
了解有关在使用库时管理工作脚本的更多信息:
¥Learn more about managing the worker script while using the library:
Managing the worker
Learn how to manage the worker script updates.
设置
¥Setup
// src/mocks/browser.js
import { setupWorker } from 'msw/browser'
import { handlers } from './handlers'
export const worker = setupWorker(...handlers)了解
setupWorkerAPI。¥Learn about the
setupWorkerAPI.
有条件地启用模拟
¥Conditionally enable mocking
最后,我们需要通过调用 worker.start() 来启动 worker,这将注册并激活 Service Worker。我们还只想在开发中启用 API 模拟,这样我们的生产流量就不会受到影响。
¥Lastly, we need to start the worker by calling worker.start(), which will register and activate the Service Worker. We also only want to enable API mocking in development so our production traffic is unaffected.
因为注册 Service Worker 是一个异步操作,所以最好将应用的渲染推迟到注册 Promise 解析为止。
¥Because registering the Service Worker is an asynchronous operation, it’s a good idea to defer the rendering of your application until the registration Promise resolves.
// src/index.jsx
import React from 'react'
import ReactDOM from 'react-dom'
import { App } from './App'
async function enableMocking() {
if (process.env.NODE_ENV !== 'development') {
return
}
const { worker } = await import('./mocks/browser')
// `worker.start()` returns a Promise that resolves
// once the Service Worker is up and ready to intercept requests.
return worker.start()
}
enableMocking().then(() => {
ReactDOM.render(<App />, rootElement)
})确保等待 worker.start() Promise!Service Worker 注册是异步的,如果未能等待,可能会导致 Worker 注册和应用发出的初始请求之间出现竞争条件。
¥Make sure to await the worker.start() Promise! Service Worker registration
is asynchronous and failing to await it may result in a race condition between
the worker registration and the initial requests your application makes.
确认
¥Confirmation
转到浏览器中的应用并在开发者工具中打开控制台。如果集成成功,你将看到打印以下消息:
¥Go to your application in the browser and open the Console in the Developer Tools. If the integration was successful, you will see the following message being printed:
[MSW] Mocking enabled.如果你没有看到此消息或看到错误,请从头开始关注此页面并确保你已完成所有步骤。
¥If you don’t see this message or see an error instead, please follow this page from the beginning and make sure you’ve completed all the steps.
相关材料
¥Related materials