Search code examples
vagrantcypress

How to run Cypress test runner in vagrant guest using host machine's browser in Ubuntu


I have a project in a vagrant box i'd like to run e2e tests on with cypress. I am able to run cypress headless within the guest machine. But I'd like the GUI features that it offers. How can I run Cypress so that it can use the host's browser to run the tests? I have Ubuntu 20.04.


Solution

  • I figured out what to do, just in case anyone else in the future needs to do this.

    Apparently for this to work, there's need for X-forwarding. That means the guest must forward the GUI display to the host.

    Assuming you have correctly installed cypress and can run it headless: yarn run cypress run (or whichever way you run it, npm etc)

    1. You need an X-Server on the host.

    • On Linux, you already have and X Server running
    • On Mac, On Mac OSX you can install XQuartz

    2. Enable X-forwarding on your Vagrant VM

    Just add this to your Vagrantfile

    config.ssh.forward_x11 = true
    

    3. Ssh into the box without vagrant ssh

    We need to access the guest with ssh as opposed to the normal vagrant ssh. Do do this: run vagrant ssh-config on the host in your directory with the vagrant file

    $ vagrant ssh-config
    Host default
      HostName 127.0.0.1
      User ubuntu
      Port 2222
      UserKnownHostsFile /dev/null
      StrictHostKeyChecking no
      PasswordAuthentication no
      IdentityFile /Users/xxxx/work/.vagrant/private_key
      IdentitiesOnly yes
      LogLevel FATAL
      ForwardX11 yes
    

    From this we have the details we need to ssh. The user, the HostName the Port and the IdentityFile.

    Now we can, from the host ssh into the guest and run the cypress test runner.

    We also need to add -X flag that tells ssh to use the X-forwarding.

    Assuming my project runs in a directory called project in the home directory of my guest machine... Run this command from the host machine while your box in running.

    ssh vagrant@127.0.0.1 -X -p 2222 -i /Users/xxxx/work/.vagrant/private_key -t "cd /home/vagrant/project; yarn run cypress open"
    

    Voila! the Test runner will run in your box and the GUI will display on your host machine.

    Credits to Gabor and Martin