[vitest+axios+msw] why can't mock '/hello' but 'http://hello' #1521
-
import { describe, expect, it, beforeAll, afterAll, afterEach } from "vitest";
import axios from "axios";
import { rest } from "msw";
import { setupServer } from "msw/node";
const server = setupServer(
rest.get("http://hello", (req, res, ctx) => {
return res(ctx.status(200), ctx.json("hello"));
}),
rest.get("/hello", (req, res, ctx) => {
return res(ctx.status(200), ctx.json("hello"));
})
);
describe("suite", () => {
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
it("msw mock http://hello", async () => {
const reponse = await axios.get("http://hello");
expect(reponse.data).toMatchInlineSnapshot('"hello"');
});
it("msw mock /hello", async () => {
const reponse = await axios.get("/hello"); //TypeError: Invalid URL
expect(reponse.data).not.toBeUndefined();
});
}); need help 😢 thanks!
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
Hi, @zhanglolo. You're getting the Note that you're running tests in Node.js (where Vitest runs), and relative URLs are not supported in Node.js! There's simply nothing to be relative to (in the browser, your URLs are relative to the current Solution
You can always read more about this in Vitest documentation or on the web. This is not an MSW issue. |
Beta Was this translation helpful? Give feedback.
-
Was getting this error because I was mocking window location like so: const windowLocationAssignMock = vi.fn();
Object.defineProperty(window, "location", {
value: {
assign: windowLocationAssignMock,
search: "?existing=parameters",
},
writable: true,
}); |
Beta Was this translation helpful? Give feedback.
Hi, @zhanglolo.
You're getting the
Invalid URL
error becausenew URL('/hello')
is indeed an invalid URL.Note that you're running tests in Node.js (where Vitest runs), and relative URLs are not supported in Node.js! There's simply nothing to be relative to (in the browser, your URLs are relative to the current
window.location
).Solution
axios
, so perhaps consider usingbaseUrl
with Axios settings so your request URLs are always absolute.