使用基本 URL
Mock Service Worker 不提供任何配置来将基本 URL 应用于多个处理程序。这样做是为了最大限度地减少配置区域,并将隐藏的复杂性排除在测试设置之外。我们强烈建议你使用自定义实用函数,这些函数可以从相对路径构建绝对 URL。这样,你既能获得实际的便利,又能保持清晰明了。
¥Mock Service Worker does not provide any configuration to apply a base URL to multiple handlers. That is a deliberate choice to minimize the configuration area and keep hidden complexity away from your test setups. Instead, we highly recommend you using custom utility functions that build absolute URLs from relative paths. That way, you get practical convenience while remaining explicit and clear.
例如,以下是如何创建一个 github() 辅助函数,用于构建针对 GitHub API 的 URL:
¥For example, here’s how you can create a github() helper for building URLs against the GitHub API:
import { http, HttpResponse } from 'msw'
function github(path) {
return new URL(path, 'https://github.com').href
}
export const handlers = [
http.get(github('/user/:login'), ({ params }) => {
return HttpResponse.json({ login: params.login })
})
]使用全局
URL构造函数来解析相对 URL。¥Use the global
URLconstructor to resolve relative URLs.