Fetch在Vitest测试中无法解析相对路径:如何模拟浏览器环境?
我在React应用中使用相对路径/api/test发起请求(通过NGINX控制器将流量路由到API或React客户端,二者共用同一基础URL)。
我在msw文档中发现相对路径是受支持的:
// Given your application runs on "http://localhost:8080",
// this request handler URL gets resolved to "http://localhost:8080/invoices"
rest.get('/invoices', invoicesResolver)Note that relative URL are resolved against the current location (location.origin).
执行console.log(window.location.origin)会输出http://localhost:3000,我认为该origin是由import '@testing-library/jest-dom'设置的。
然而,当我在测试(msw正在模拟API调用)中发起fetch请求时,会收到TypeError: Invalid URL: /api/test错误。
发起请求的代码:
fetch('/api/test') .then((response) => response.json()) .then((data) => console.log(data))
错误信息:
Vitest caught 1 unhandled error during the test run. This might cause false positive tests. Resolve unhandled errors to make sure your tests are not affected. ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Unhandled Rejection ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ TypeError: Failed to parse URL from /api/test ❯ new Request node:internal/deps/undici/undici:9474:19 ❯ FetchInterceptor.<anonymous> node_modules/@mswjs/interceptors/src/interceptors/fetch/index.ts:42:23 ❯ step node_modules/@mswjs/interceptors/lib/interceptors/fetch/index.js:59:23 ❯ Object.next node_modules/@mswjs/interceptors/lib/interceptors/fetch/index.js:40:53 ❯ node_modules/@mswjs/interceptors/lib/interceptors/fetch/index.js:34:71 ❯ __awaiter node_modules/@mswjs/interceptors/lib/interceptors/fetch/index.js:30:12 ❯ globalThis.fetch node_modules/@mswjs/interceptors/src/interceptors/fetch/index.ts:41:42 ❯ App src/App.tsx:9:3 7| 8| function App() { 9| fetch('/api/test') | ^ 10| .then((response) => response.json()) 11| .then((data) => console.log(data)) ❯ renderWithHooks node_modules/react-dom/cjs/react-dom.development.js:16305:18 This error originated in "src/App.test.tsx" test file. It doesn't mean the error was thrown inside the file itself, but while it was running. Caused by: TypeError: Invalid URL: /api/test ❯ new URLImpl node_modules/whatwg-url/lib/URL-impl.js:21:13 ❯ Object.exports.setup node_modules/whatwg-url/lib/URL.js:54:12 ❯ new URL node_modules/whatwg-url/lib/URL.js:115:22 ❯ new Request node:internal/deps/undici/undici:9472:25 ❯ FetchInterceptor.<anonymous> node_modules/@mswjs/interceptors/src/interceptors/fetch/index.ts:42:23 ❯ step node_modules/@mswjs/interceptors/lib/interceptors/fetch/index.js:59:23 ❯ Object.next node_modules/@mswjs/interceptors/lib/interceptors/fetch/index.js:40:53 ❯ node_modules/@mswjs/interceptors/lib/interceptors/fetch/index.js:34:71 ❯ __awaiter node_modules/@mswjs/interceptors/lib/interceptors/fetch/index.js:30:12
在浏览器中运行代码时没有任何问题。既然document.baseURI和window.location.origin已设置,fetch是如何“识别”它并非运行在浏览器中的?是否可以通过设置window的其他字段来避免该错误?
内容的提问来源于stack exchange,提问作者BPDev

