Closed bogdan-pechounov closed 1 year ago
In node, there is no domain. You cannot run any relative requests from node - you will always need a full url for your tests if they don't run in a browser.
I see. I thought it could be faked by setting a field in document
, but it seems to be more complicated than this. example
Edit: I found in the msw documentation that relative paths are supported.
// 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).
If I console.log(window.location.origin)
, it also prints http://localhost:3000
. I tried using fetch
and it throws the same error TypeError: Failed to parse URL from /api/test
, so it's not an issue with RTK Query.
@bogdan-pechounov I'm having same issue, were you able to resolve it?
@abbas-dhd The base query needs to be a full path baseQuery: fetchBaseQuery({ baseUrl: window.location.origin + '/api/auth' })
. The mock handler can still use a relative path.
rest.get('/api/auth/me', (req, res, ctx) => {
console.log('REQUEST')
return res(ctx.status(200), ctx.json({ username: 'User' }))
}),
One comment on my side: @phryneas is completely right—there are no relative URLs in Node.js, nothing to be relative to! MSW doesn't claim it supports it either. What MSW tells you is that if you are using browser-like environments in Node.js (like JSDOM), those environments will polyfill the global location
and then MSW will be able to resolve relative URLs against that location similar to how it does so in the browser.
I solved it by setting base URL in .env files. and had a mock URL in .env.test
something like http://www.example.com
. since I was using MSW only while running unit tests it would take full mock URL.
I've updated MSW docs to include two things:
I hope this helps folks get to the root cause and the fix faster now.
Since I have an NGINX controller routing requests to either the api or the react client, both the api and the client have the same base url. Therefore, I can make requests to
/api/auth/me
instead ofhttp://localhost/api/auth/me
. authApi.tsThere are no issues when starting a server, but when I run tests with msw mocking api calls, I get an error.
I am not sure why it happens since even the baseURI is faked:
console.log(document.baseURI)
printshttp://localhost:3000/
. If I usehttp://localhost/api/auth
instead of/api/auth
, there are no errors, but I would prefer avoiding setting the baseUrl for production and development if possible.repo: https://github.com/bogdan-pechounov/microservices-quiz-app/tree/8983e6456e00967896adbdb30b47f6af7be1bd08 directory: react-client commands: npm install npm test
(To run it, use the skaffold.yaml file to start the apis as well.
skaffold run -f skaffold.dev.yaml
)