XMLHttpRequest 进度事件

支持 XMLHttpRequest 的进度事件。

限制 中所述,由于 Service Worker API 的设计,MSW 的浏览器集成不支持 XMLHttpRequest 上的进度和上传进度事件。你可以通过在工作进程之前拦截 XMLHttpRequest 来绕过此限制,并使用 @mswjs/interceptors 中的 XMLHttpRequestInterceptor

¥As stated in the Limitations, the browser integration of MSW does not support the progress and upload progress events on XMLHttpRequest due to the Service Worker API design. You can circumvent that limitation by intercepting XMLHttpRequest earlier than the worker does, using the XMLHttpRequestInterceptor from the @mswjs/interceptors.

// mocks/xhr.ts
import { getResponse } from 'msw'
import { XMLHttpRequestInterceptor } from '@mswjs/interceptors'
import { handlers } from './handlers' // Import your request handlers
 
const interceptor = new XMLHttpRequestInterceptor()
 
interceptor.on('request', ({ request, controller }) => {
  const response = await getResponse(handlers, request)
 
  if (response) {
    controller.respondWith(response)
  }
})
 
interceptor.apply()
// mocks/browser.ts
import './xhr'
 
// The rest of your browser setup for MSW here.
// (e.g. `setupWorker`, `handlers`, etc.)

在上面的示例中,你可以通过 getResponse 函数将现有的 handlers 解析为 XMLHttpRequestInterceptor。这样,你的设置保持不变,你仍然可以像往常一样编写请求处理程序,但需要将它们传递给这个手动拦截器。XMLHttpRequestInterceptor 会修补 XMLHttpRequest 类,这意味着 XMLHttpRequest 将不再对 Service Worker 可见。你的其余处理程序不受此影响。

¥In the example above, you can resolve your existing handlers against the XMLHttpRequestInterceptor via the getResponse function. This way, your setup stays the same, you still write your request handlers as you are used to, but pass them through this manual interceptor. The XMLHttpRequestInterceptor patches the XMLHttpRequest class, which means that XMLHttpRequest will not be visible to the Service Worker anymore. The rest of your handlers are not affected by this.

相关资源

¥Related resources