Executing System Command in Cypress Tests

Photo by Darren Halos on Pexels.com

Recently, I wrote a Cypress test where I had to copy a configuration file from one container to another container. As you may know, the easiest way to do that is to use the “docker cp” command. This post is a step-by-step how-to I used to achieve this.

Installing Docker

The “tester” container is based on the official cypress/included:6.3.0 docker image, which in turn is based on the official node:12.18.3-buster docker image. So as the first step, I had to figure out how to install Docker in Debian 10 in order to be able to run “docker cp” from within the container:

FROM cypress/included:6.3.0

RUN apt-get update && apt-get install -y \
  apt-transport-https \
  gnupg2 \
  software-properties-common

RUN curl -fsSL https://download.docker.com/linux/debian/gpg | apt-key add -

RUN add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/debian buster stable"

RUN apt-get update && apt-get install -y \
  docker-ce

Creating a Volume for the /var/run/docker.sock

In order to talk to the Docker daemon running outside of the “tester” container, I had to add a volume to mount the famous /var/run/docker.sock in the docker compose file:

volumes:
  - /var/run/docker.sock:/var/run/docker.sock

Executing “docker cp” in Cypress Test

Finally, I was able to execute “docker cp” to copy the configuration file from the “tester” container to the “web_app” container using the Cypress exec command:

const configYamlPath = 'cypress/fixtures/config.yaml';

cy.exec(`docker cp ${configYamlPath} web_app:/opt/web_app`)
  .then(() => cy.reload());

Want to buy me a coffee? Do it here: https://www.buymeacoffee.com/j3rrywan9