Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cypress can't load assets from Vite's devserver

I have an app running at http://localhost/ which loads it's assets from a Vite's devserver which is up at http://localhost:3000/. Cypress is hitting the main app correctly, but it doesn't load the assets, leaving me with a blank page because the page received no response for the http://localhost:3000/app.js file.

Everything works fine if I visit the app directly on the browser. The browser is able to load the assets from port 3000 without problems. They're only failing when requested via the Cypress test runner.

enter image description here

I tried to cy.visit('http://localhost:3000/') and it seems like the Vite's devserver is refusing connections. But I checked the Vite documentation to see if there was something that could be blocking this and nothing caught my eyes. Also, the strange part is that they're only blocked when requested via the test runner.

enter image description here

I'm running Cypress on WSL2 and my app and the Vite devserver are running through Docker mapping to the addresses above. Is there any additional configuration I'm missing?

If I build the assets and serve them from the main app address (http://localhost/dist/app.js), everything works fine and my tests run fine. So, I'm guessing there's some sort of configuration I need to do to allow Cypress to request assets form other hosts?

like image 979
Matheus Dal'Pizzol Avatar asked Oct 24 '25 22:10

Matheus Dal'Pizzol


2 Answers

It seems to be due to Vite by default only accepting requests made using the 'localhost' hostname.

On the other hand, Cypress interprets 'localhost' as '127.0.0.1', so when interpreting cy.visit('http://localhost:3000/') it actually runs cy.visit('http://127.0.0.1:3000/'). But Vite won't accept "127.0.0.1".

The best solution I've found is to open your Vite config file (like vite.config.js) and add the following within defineConfig:

server: {
  port: 5173,
  host: '127.0.0.1'
}

This will make Vite expose the host '127.0.0.1' directly instead of 'localhost', and both 'localhost' and '127.0.0.1' will be accepted by the Vite server.

like image 169
Evan Avatar answered Oct 26 '25 11:10

Evan


The problem was in the docker-compose.yml file.

I had exposed VITE's port with EXPOSE 3000 on the Dockerfile, but not in the ports: of the docker-compose.yml.

And since it was working on the browser, I assumed that mapping on the docker-compose.yml was redundant.

This was originally posted by Matheus Dal'Pizzol as a comment.

like image 27
2 revs, 2 users 67%user22438867 Avatar answered Oct 26 '25 12:10

2 revs, 2 users 67%user22438867



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!