Skip to content

[vitest+axios+msw] why can't mock '/hello' but 'http://hello' #1521

Answered by kettanaito
zhanglolo asked this question in Q&A
Discussion options

You must be logged in to vote

Hi, @zhanglolo.

You're getting the Invalid URL error because new 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

  • Use the absolute request URL. In your case, you're using axios, so perhaps consider using baseUrl with Axios settings so your request URLs are always absolute.

Note that certain testing frameworks, like Jest, automatically polyfill window.location which may give you a false impression that relative URLs are okay in Node. They are okay only because the t…

Replies: 2 comments 5 replies

Comment options

You must be logged in to vote
3 replies
@zhanglolo
Comment options

@zhanglolo
Comment options

@kettanaito
Comment options

Answer selected by kettanaito
Comment options

You must be logged in to vote
2 replies
@MartinYounghoonKim
Comment options

@Maxim-Mazurok
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants