This Cypress Docker tutorial will help you learn how to simplify and streamline your testing process with Cypress and Docker.
OVERVIEW
Automation testing and Continuous Integration (CI) have become essential components of the development and testing process in today's software development process.
As a result, the use of Docker in CI/CD pipelines is becoming increasingly popular, as it allows for seamless integration of automation testing with the rest of the development workflow.
When combined with Cypress, it can further simplify the testing process. This means that automation engineers can use a Docker container that includes Cypress and all the necessary dependencies and use that container to run their automated tests in a consistent environment, regardless of where the tests are being run.
This Cypress Docker tutorial will help you learn how to simplify and streamline your testing process with Cypress and Docker.
Docker is an open-source software platform that uses OS-level virtualization and helps you create, deploy, and run applications securely using containers.
These containers are like virtual boxes that keep your software parts organized and separate from each other and add an extra layer of security.
Docker runs as a discrete process on the host machine, providing a stable and predictable environment for the application. Its flexibility allows it to be run on local machines that run Windows, Mac, or Linux, as well as on cloud infrastructure like AWS, Azure, and others. You can learn more about it through this blog on running tests in Docker.
Docker has become the go-to DevOps platform for software engineers worldwide, providing a consistent, reliable testing experience. By using Cypress with Docker to run your tests, you can achieve several benefits.
Before we dive deep into the usage of Docker with Cypress, let’s understand the basics first.
Run Cypress Docker Tests Online. Try LambdaTest Now!
A Dockerfile is a script containing a set of commands used to create a Docker image. It serves as a guide for Docker to build an image by providing a sequence of instructions. These instructions are executed to produce the final Docker image.
Using a Dockerfile allows automation engineers to define and automate the steps required to create a Docker image, which can then be used to deploy the application in a containerized environment.
By using a Dockerfile to create a Docker image, you can easily set up a reproducible environment for running your tests. You can also easily share the Docker image with other automation engineers to ensure that everyone is running the tests in the same environment.
While doing automation, it's very common to encounter scenarios where a test case works flawlessly on one system but fails to perform as expected on another employee's system. These discrepancies can cause confusion and delay. However, by utilizing a Dockerfile, these situations can be easily avoided.
A Dockerfile allows automation engineers to create a container that includes all the necessary dependencies and libraries needed to run a software application. This means that automation engineers can create an environment consistent across all machines and avoid dependency issues that might cause tests to fail on one system but not another.
A Docker image is a snapshot of a container created by building a Dockerfile. It can be an existing image created by someone else or a new image created by you. Essentially, it is a lightweight, standalone, and executable package that includes all of the dependencies, configuration files, and application code needed to run your application.
Docker image contains all the necessary dependencies, such as Library, Configuration files, and Code. It is a read-only template that includes instructions for creating a Docker container. It can be created from scratch or based on an existing image. Docker images are stored in a Docker registry such as Docker Hub, a public repository of Docker images.
To create a Docker image, a Dockerfile can be used to define the instructions for building the image. Once the Dockerfile is created, the docker build command can be used to build the Docker image. The resulting image can then be pushed to a Docker registry, such as Docker Hub, for others to use.
Overall, Docker image is a self-contained package that includes everything needed to run an application, and it is created by building a Dockerfile using the docker build command.
Below are the Cypress Docker images available as of April 2023:
A Docker container is a live execution of a Docker image. It is an enclosed environment that bundles code and all its dependencies into a single, portable package. It is a lightweight and self-contained entity that comprises everything required to run an application.
At the application level, containers serve as an abstraction, completely unaware of the host's operating system or files. Instead, they leverage the environment provided by Docker Desktop, which includes a base operating system and all the dependencies needed to execute the application.
Containers are engineered to be lightweight, with all the essential components required to run an application, eliminating any dependencies on pre-existing software on the host machine. Multiple containers can run on the same machine and share the operating system kernel with other containers, each running as isolated processes in user space.
They are easy to share while you work, and you can be sure that everyone you share with gets the same container that works in the same way. This makes it easy to test applications across different environments.
Docker is a popular containerization platform that offers several advantages, including:
Portability
Docker containers can run on cross-platform, including software engineers' laptops, data centers, and public clouds. This means that automation engineers can build and test applications locally and then deploy them seamlessly to the CI/CD pipeline.
Scalability
Because Docker containers are lightweight and run in isolation, they can be easily replicated and scaled up or down as needed to meet changing demands. This makes it easier to manage infrastructure resources efficiently and cost-effectively.
Security
Docker containers provide a high level of security and reliability as each container runs in its isolated environment, which helps prevent conflicts between applications and services.
Efficiency
Docker containers are lightweight and consume fewer resources than traditional virtual machines, making them more efficient. This allows software engineers to run multiple containers on a single host without any performance degradation.
Consistency
Docker containers provide a consistent environment for applications, ensuring that they run the same way across different systems, regardless of the underlying infrastructure. This ensures that the application behaves the same way in all environments.
Using Docker with Cypress for end-to-end testing is a great way to ensure consistent and reliable testing results. By packaging your tests and their dependencies into a Docker container, you can easily move your tests between environments, run tests in parallel, and deploy tests to the cloud while performing Cypress end-to-end testing.
Below are some reasons why using Docker with Cypress can be beneficial:
Isolation
By running Cypress in a Docker container, you can ensure that your test environment is completely isolated from the host machine and any other dependencies like Node.js, Cypress and specific browser versions.
This means that even if you don't have Node.js or a specific browser version installed on your computer, you can still run the Cypress test case using the Cypress Docker image to ensure that your tests behave the same way on all machines. This prevents conflicts and ensures that tests are run in a consistent environment every time.
Using Docker, you don’t need to rely on the dependency to run the Cypress test. For example, if you want to run a test on Cypress version 12.9.0 and Chrome version 111.0.5563.146 but don’t have the same Cypress version and browser version available on your system. In that case, you can simply use pre-built Cypress- Docker image cypress-12.9.0-node-18.14.1-chrome-111.0.5563.146-1-ff-111.0.1-edge-111.0.1661.54-1, which has the respective Cypress version and Chrome browser available. This makes it easy to migrate your tests between machines and environments without worrying about installation or cross-platform issues.
Reproducibility
Docker allows you to create a consistent testing environment that can be easily reproduced across multiple operating systems. This helps ensure that your tests behave consistently, regardless of the operating system they are run on.
One of the primary benefits of using Docker for test automation is that it helps avoid common issues that can arise when executing tests across different systems. For example, you may experience problems when a test suite runs smoothly on your local machine but fails on your colleague's machine due to differences in browser version, Cypress version, and other factors.
Consider a scenario where you are running tests on Cypress version 12.0, but your colleague is still using an older version, such as Cypress version 9. In this situation, certain configurations may not work on their machine since Cypress version 9 and version 12.0 have different folder structures. However, Docker image can come to your rescue by ensuring that your tests are executed in a consistent and reproducible environment, regardless of the underlying system.
Portability
With Docker, you can easily move your Cypress tests and their dependencies between different machines and environments without worrying about setting up and configuring the environment each time.
Scalability
In addition to enabling the creation of a consistent testing environment, Docker makes it easy to run multiple instances of Cypress tests in parallel on the same machine or across multiple machines. There are pre-configured Cypress Docker images available in the Docker Hub registry. This Cypress Docker image contains all the dependencies and configurations required to run Cypress tests in a Docker container, making it easier to create a consistent testing environment across different systems.
Docker provides the capability to run multiple instances of Cypress tests in parallel on a single machine or across multiple machines.
This is made possible by Docker images designed specifically for test automation. These images contain all the necessary dependencies and configurations required for executing tests and can be spun up quickly, thus allowing for the rapid execution of tests across multiple instances.
By leveraging Docker images for test automation, you can significantly accelerate the testing process and reduce the overall test execution time, leading to faster time-to-market and improved product quality. This can help speed up your testing process and reduce the overall test execution time.
Also, explore our comprehensive guide on test execution engines, gaining insights into their functionalities to elevate your testing workflow with automation.
Easy Deployment
By packaging your Cypress tests and their dependencies into a Docker container, you can easily deploy your tests to any Docker-compatible environment, such as a cloud service provider or a Kubernetes cluster, without having to worry about installation or configuration issues.
For example, if you plan to run your tests on a CI/CD platform like Jenkins, you may need to install Node.js on Jenkins. However, by utilizing the Cypress Docker image, you can avoid this requirement and simply use Docker commands in your Jenkins pipeline.
Incorporating the Cypress Docker image into your CI/CD pipeline is a hassle-free way to automate the testing process and expedite the feedback loop for code modifications. With this image, you can easily create numerous containers to run tests in parallel, decreasing the overall time for test execution and facilitating faster iterations.
"Streamline your software development and integration process with the LambdaTest Docker integration. Seamlessly incorporate software applications into your current workflows"
To get started with Cypress Docker, you will need to install Docker on your machine. Below are the steps that can be followed to install and set up Docker.
Step 1: Go to the official Docker website and download it as per your OS (Windows/Mac/Linux).
Step 2: Install Docker.
Step 3: Launch Docker by double-clicking on it.
Step 4: Verify Docker installation by going to the terminal (Mac machine)/command-prompt (Windows) and entering the command:
docker --version
If you see the Docker version message (like the one shown in the screenshot below), that means Docker is installed successfully on your system
Step 5: After installing and verifying Docker on the machine, let's start Docker now. You can start by simply clicking on Docker. It will open the window like shown below:
If you see the above window, that means Docker is ready to run containers.
Downloading and running Cypres involves just 1 step (if you have Node.js installed), but what if you don’t have Node.js/Cypress installed on your machine? It can be a hassle to set up the necessary environment.
This is where Docker comes in handy, allowing you to run Cypress tests on your local machine with just one Docker command without worrying about installing Cypress and Node.js.
The Docker image contains both Cypress and OS dependencies, which can be used to run Cypress tests. As of writing this Cypress Docker tutorial, four images are provided for running Cypress in Docker.
In this section of this Cypress Docker tutorial, we will be using cypress/included (the latest version of cypress/included is 12.8.1 at the time of writing the Cypress Docker tutorial). This Docker image comes with all operating system dependencies, Cypress, and browsers like Chrome and Firefox installed globally)
There are multiple ways in which Cypress tests can be run in Docker containers. One of the ways is to run using the following command from the root of your project:
docker run -it -v $PWD:/e2e -w /e2e cypress/included:12.8.1
Here's how you can run Cypress tests using a Docker image. Let's understand with an example.
Test Scenario
|
Implementation
describe("Automation using Cypress", () => {
it("Login into web app , search for product and verify it", () => {
cy.visit("https://ecommerce-playground.lambdatest.io/index.php?route=account/login");
cy.get('[id="input-email"]').type("lambdatest.Cypress@disposable.com");
cy.get('[id="input-password"]').type("Cypress123!!");
cy.get('[type="submit"]').eq(0).click();
cy.get('[name="search"]').eq(0).type("Macbook");
cy.get('[type="submit"]').eq(0).click();
cy.contains("Macbook");
});
});
Execution
Start the Docker and go to your Cypress project. Open the terminal and run the below command:
docker run -it -v $PWD:/e2e -w /e2e cypress/included:12.8.1
File Walkthrough
The above command is useful for running Cypress tests in a containerized environment, with the option to mount the current working directory as a volume so that changes made on the host system are reflected inside the container.
Here, PWD refers to your Cypress project’s root directory.
To ensure consistency and avoid potential issues, it is advisable to use a particular image tag rather than relying on the default tag. This is because the default tag can change over time as new versions of the image are released. If you use the default tag, your application may inadvertently use a different version of the image than the one you intended, potentially causing compatibility issues or other problems.
By using a specific image tag, such as "cypress/included:12.8.1", you ensure that your application always uses the same version of the image. This can help to prevent unexpected behavior and make it easier to troubleshoot any issues that arise.
In addition, using a specific image tag also makes it easier to track changes and maintain consistency across your infrastructure. If you need to update your application to use a new version of the image, you can simply update the tag in your configuration rather than manually track and update the image version number.
As shown in the screenshot, the system is attempting to locate the Cypress Docker image. It first checks if the image is already downloaded on your system. If it is not found, the system will attempt to download the image from Docker Hub
As shown in the screenshot below, you can run your Cypress test with a single Docker command. It is important to note that by default, the Cypress test runs in the Electron browser in headless mode, but while running it in headed mode, you can choose any supported browser of your choice from the Cypress test runner screen.
You can also check the container status after running the command using the command:
docker ps -a
Deliver immersive digital experiences with Next-Generation Mobile Apps and Cross Browser Testing Cloud
Running Cypress tests on specific browser versions can be necessary to ensure compatibility with the target environment. Different browsers like Firefox and Chrome may have varying feature sets and behaviors that can affect the test results.
By default, Cypress runs the tests on the Electron browser, but if you want to run Cypress tests on Chrome and Firefox browsers using a Docker image, then you can follow the below detailed steps.
We will use the same test case used in the last step to run the Cypress test using Docker. To run the Cypress test locally on your machine using the Docker image, use the below command:
docker run -it -v $PWD:/e2e -w /e2e cypress/included:12.8.1 --browser firefox
By using the command provided above, the Cypress test will be carried out in headless mode on the Firefox browser, specifically using the version currently installed on the local machine. This will ensure that all e2e tests are executed seamlessly.
To run the test case on the Chrome browser, you just need to change the browser name in the same command.
docker run -it -v $PWD:/e2e -w /e2e cypress/included:12.8.1 --browser chrome
By utilizing the command provided above, the Cypress e2e test will be executed in headless mode on the Chrome browser (on the version currently installed on the local machine).
In the next section of the Cypress Docker tutorial, we will learn how to run Cypress tests on specific browser versions.
In addition to executing Cypress tests with the command mentioned earlier, Dockerfile can also be utilized for the same purpose. This approach offers several benefits, including the ability to pass custom scripts from the package.json file and run them with Dockerfile.
One of the primary advantages of using Dockerfile for Cypress testing is that it offers greater flexibility in terms of customization. For the scenario in this Cypress Docker tutorial, we will be using the cypress/factory Docker image, which Cypress recently released.
This image can be used with Docker args to generate a Docker container with specific versions of Node, Cypress, and browsers like Chrome, Firefox, and Edge. Using this Docker image, you can test multiple browser versions.
The same can be achieved using cypress/included as well, but here, we are opting to use cypress/factory as it is a newly released option from Cypress and is particularly well-suited for generating a customized Docker image.
Now, let’s create a Dockerfile and run a Cypress test on a specific version of Chrome and Firefox browsers.
Create a Dockerfile at the root of your project.
Pass the below code in Dockerfile.
ARG CHROME_VERSION='107.0.5304.121-1'
ARG EDGE_VERSION='100.0.1185.29-1'
ARG FIREFOX_VERSION='107.0'
FROM cypress/factory
WORKDIR /app
COPY . .
RUN npm install --save-dev cypress
After creating a Dockerfile, you need to build the Docker image using the command:
docker build -t cypress-test-browser
After building, you can now run the Cypress test in Docker using the below command:
docker run -it cypress-test-browser -b chrome
You can also pass the args in the Docker build command. In that case, just change the Dockerfile content as shown below. (just remove Args instructions in Dockerfile)
FROM cypress/factory
WORKDIR /app
COPY . .
RUN npm install --save-dev cypress
To build the above Dockerfile, use the command:
docker build . --build-arg CHROME_VERSION='107.0.5304.121-1' --build-arg EDGE_VERSION='100.0.1185.29-1' --build-arg FIREFOX_VERSION='107.0' -t cypress-test-browsers
The above command initiates the build process for a Docker image. The build command takes the Dockerfile in the current directory (specified by the dot "."), and uses the specified build arguments (--build-arg) to set the versions of Chrome, Edge, and Firefox to be installed in the container. The -t flag sets the name of the resulting Docker image as "cypress-test-browsers".
It will run your test on the specified Chrome and Firefox versions only. You can pass it in the command to run it on different versions. The exact version must be used; no wildcards or shorthands are supported. You can pass any stable version of Chrome and Firefox in Dockerfile.
To run the Cypress test using the above shared Dockerfile, you can use the below command:
docker run cypress-test-browsers npm run cypress-test-browsers -b chrome
The above command runs a Docker container based on the previously built image "cypress-test-browsers". The "npm run cypress-test-browsers -b chrome" command is executed inside the container, which invokes Cypress to run tests in the Chrome browser.
To execute the tests on the Firefox browser, simply include the flag "-b firefox" in the command. This will cause the tests to run on the Firefox browser version specified in the build command.
Running Cypress tests with Docker can help catch and fix issues early in the development process, saving time and resources down the line. By enabling early detection and resolution of bugs, this approach can streamline the development process and deliver reliable software with greater speed and efficiency.
The last approach in this Cypress Docker tutorial was running a Cypress test in Docker on your local machine using a Docker command, but what if you want to use a customized script and run it using Docker? In that case, you can use Dockerfile.
There are two approaches for using Dockerfile in Cypress:
Below is a step-by-step guide to creating a Dockerfile from scratch and running the Cypress test cases using Dockerfile.
Step 1: Open up the Integrated Development Environment (IDE) of your choice, like Visual Studio Code, and go to the project directory. Once there, create a new file at the root level of your project directory and name it Dockerfile (without any file extension).
Step 2: Add the below code to the Dockerfile.
Let’s understand the commands used in the above Dockerfile.
One important detail to keep in mind is that if the specified directory ("/app" in this case) does not already exist, the "WORKDIR" instruction will create it. Additionally, any "COPY" or "ADD" commands that come after the "WORKDIR" instruction will be executed relative to the specified working directory. Here, we have passed the name as /app, but any name can be passed as directoryName.
The first “.” refers to the source directory on the host machine, and the second “.” refers to the destination directory within the container.
After creating a Dockerfile, let’s explore the process of building a Dockerfile, pushing it to a registry, and then running it.
To build the Docker image, navigate to the directory containing your Dockerfile and run the following command:
docker build -t <image_name>
For example:
docker build -t cypress_docker
On running the above command, you will see the building process just as shown in the screenshot below:
Once it is successfully built, there will be a successful message on the terminal (just as shown in the screenshot below):
After the Docker image is built, you can verify by running the command:
docker images
You can now run the Docker image after building it by using the following command:
docker run imagename:tagname
For example:
docker run cypress_docker latest
This will run all the test cases in headless mode (it will perform npx cypress run)
The Docker Compose file is a YAML file that defines how Docker containers should be built, configured, and run as a single service or application. With the Docker Compose file, you can define multiple containers and their configuration in a single file, making it easier to manage and deploy complex Cypress testing environments
For example, a Docker Compose file can be used to set up multiple containers for running Cypress tests on different browsers, such as Chrome, Firefox, and Edge. Each container can be configured with the specific browser and version needed for the tests. This means that you can run the same tests across multiple browsers simultaneously, making it easier to identify browser-specific issues.
The advantage of using docker-compose.yml is that you can use a single file to run Cypress test cases on multiple browsers using a single command. When you run the docker-compose up command, it will spin up three separate containers - one for each browser - and run the Cypress tests in parallel within these containers.
Prerequisite:
Install Docker Desktop
Let’s follow the step-by-step process to run the test cases - LoginPage.js and HomePage.js on Chrome, Firefox, and Edge at the same time using a single file, we will use docker-compose.yml.
Create a file named docker-compose.yml at the root of your project, just like shown below:
Add the content to docker-compose.yml.
File Walkthrough
The above-shared file is a Docker Compose file for running Cypress tests on multiple browsers. It has three services, each of which uses the cypress/included Docker image version 12.8.1 to run Cypress tests in different browsers. The services are named cypress-chrome, cypress-firefox, and cypress-electron, respectively.
cypress-chrome:
image: cypress/included:12.8.1
command: "--browser chrome"
working_dir: /cypress
volumes:
- ./:/cypress
This defines a service called cypress-chrome that runs the Cypress tests on Google Chrome. It uses the cypress/included:12.8.1 Docker image as the base image, which includes Cypress pre-installed.
The command specifies that it should run in Chrome, and the working_dir sets the working directory to /cypress. Finally, the volumes section mounts the current directory (represented by ./) as a volume inside the container at the /cypress directory, allowing the container to access the Cypress tests.
cypress-firefox:
image: cypress/included:12.8.1
command: "--browser firefox"
working_dir: /cypress
volumes:
- ./:/cypress
cypress-electron:
image: cypress/included:12.8.1
working_dir: /cypress
volumes:
- ./:/cypress
Once you create docker-compose file, You can run it using the below command:
docker-compose up
By running your test case in headless mode, you lose the chance to observe the execution process. However, with Cypress, you can preserve videos of the test case. Furthermore, if you run your test case using docker-compose up within a Docker container, you can still watch the videos.
To accomplish this, we define a volume in the docker-compose.yml file that maps data from the Docker container to a specified path. In this case, all the data is copied from the container to /cypress. As a result, the Cypress test execution video is transferred from the Docker container to the cypress/videos directory.
Once the test execution is complete, you can view the videos of the test execution, similar to the example below.
Apart from checking videos, you can also view the test execution using VNC Viewer, a tool that allows you to view the graphical desktop of a remote machine.
Cypress automation on a cloud-based testing digital experience testing platform like LambdaTest helps you attain accelerated test execution as well as improved browser coverage while performing Cypress testing on over 50+ browsers and OS combinations. In addition, you can fasten the release cycle up to 10x with Cypress parallel testing.
Check our documentation to get started with Cypress testing on LambdaTest.
You can also visit the below Cypress tutorial to get started with Cypress automation.
Subscribe to our LambdaTest YouTube Channel to get the latest updates on tutorials around Selenium testing, Cypress testing, Appium, and more.
There are multiple ways to perform Cypress UI testing on a cloud testing platform like LambdaTest. One of them is using Docker.
Below is the Cypress end-to-end testing code, which we will run in the LambdaTest cloud platform.
describe("Automation using Cypress", () => {
it("Login into web app , search for product and verify it", () => {
cy.visit("https://ecommerce-playground.lambdatest.io/index.php?route=account/login");
cy.get('[id="input-email"]').type("lambdatest.Cypress@disposable.com");
cy.get('[id="input-password"]').type("Cypress123!!");
cy.get('[type="submit"]').eq(0).click();
cy.get('[name="search"]').eq(0).type("Macbook");
cy.get('[type="submit"]').eq(0).click();
cy.contains("Macbook");
});
});
To run the Cypress tests on the LambdaTest Platform, we need to do the configuration using three steps.
Step 1: Install LambdaTest CLI.
Install LambdaTest CLI using npm by using the below command:
npm install lambdatest-cypress-cli
Step 2: Set up the config.
Once the LambdaTest CLI is installed, we need to set up the configuration using the below command:
lambdatest-cypress init
After running the command, there will be a file created in your project named “lambdatest-config.json”. We need to set up the configuration to run our test case on different browsers on LambdaTest.
For Cypress version 10 and above, you can follow the below code to set up lambdatest-config.json.
{
"lambdatest_auth": {
"username": "user.name",
"access_key": "access.key"
},
"browsers": [
{
"browser": "Chrome",
"platform": "Windows 10",
"versions": [
"latest-1"
]
},
{
"browser": "Firefox",
"platform": "Windows 10",
"versions": [
"latest-1"
]
}
],
"run_settings": {
"config_file": "cypress.config.js",
"reporter_config_file": "base_reporter_config.json",
"build_name": "Cypress-Test",
"parallels": 1,
"specs": "./cypress/e2e/*.cy.js",
"ignore_files": "",
"network": false,
"headless": false,
"npm_dependencies": {
"cypress": "12.7.0"
}
}}
Step 3: Execute test case.
Once the config is done, you can execute the Cypress test case on the LambdaTest Cypress Cloud. You just need to run the below command to run it on LambdaTest.
lambdatest-cypress run
After the command is run and test cases are executed successfully, you can view the Cypress test run on the LambdaTest cloud platform (as shown in the screenshot below):
Until now, in this Cypress Docker tutorial, we learned how to perform Cypress UI automation on the LambdaTest cloud platform using the IDE terminal. Let’s see how to run the above flow using Cypress with Dockerfile.
To run it using Docker, we will use the Dockerfile in which you can pass the script, defined in package.json.
You need to create a script in package.json. To run the Cypress test on the LambdaTest cloud platform, we need to run the command “lambdatest-cypress run”.
The same command we will create as a script in package.json just as shown below:
{
"name": "cypress_withdocker",
"version": "1.0.0",
"description": "Cypress test using Docker",
"main": "index.js",
"scripts": {
"cypress-test-cloud": "lambdatest-cypress run"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Anshita-Bhasin/Cypress_WithDocker.git"
},
"author": "Anshita Bhasin <anshita@propertyfinder.ae>",
"license": "ISC",
"bugs": {
"url": "https://github.com/Anshita-Bhasin/Cypress_WithDocker/issues"
},
"homepage": "https://github.com/Anshita-Bhasin/Cypress_WithDocker",
"dependencies": {
"cypress": "^12.9.0",
"lambdatest-cypress-cli": "^3.0.11"
}
}
To test if the above script is working fine, Go to the terminal and execute the command:
<npm run scriptname>
For the above code, the command would be npm run cypress-test-cloud. If you see the tests result just as shown below, your script is working fine.
To run the same using Dockerfile, follow these steps:
FROM cypress/included:12.8.1
WORKDIR /app
COPY . .
RUN npm install
ENTRYPOINT ["npm","run", "cypress:test:cloud"]
File Walkthrough:
This Command runs the cypress command to execute the Cypress tests. It will check in package.json if there is a command with the name cypress-test-cloud, and then it will run, else it will throw an error.
After creating a Dockerfile, the next step is to build a Dockerfile to run it. Make sure to start the Docker before building it. Just open Docker Desktop on your machine, and you should be logged in.
Building the Docker image
To build the Docker image using this Dockerfile, you can run the following command in the directory containing the Dockerfile:
docker build -t <image_name>
For example:
docker build -t cypress_example:v1
On running the above command, you would see the building process just as shown in the screenshot below:
Once it is successfully built, there will be a successful message on the terminal that the build is FINISHED.
Once the Docker image is built, you can verify its presence by running the below command:
docker images
This command lists all the Docker images currently available on your local machine.
After building the Docker image, you can push it. However, you may encounter an access denied issue despite being logged in. In such a situation, you can resolve the problem by tagging the image and then pushing it. Before attempting to push, ensure that you have logged in by running the below command:
docker login
Tag the image using the below command:
docker tag imagename:tag dockerUsername/imagename:tag
For example:
docker tag cypress_example:v1 anshita1012/cypress_example:v1
It is important to note username refers to your Docker Hub account username, which is used for logging into Docker Hub. You can find your Docker Hub account username by logging into Docker Desktop and looking at your profile information.
The next step is to push the docker image. This is used to upload a Docker image from your local machine to a Docker registry, such as Docker Hub or a private registry. Once an image is pushed to a registry, it can be downloaded and used by others, either for running containers or as a base image for building new images.
To push the docker image, you can use the below command:
docker push dockerUsername/image-name:v1
For example:
docker push anshita1012/:v1
The above command will push the image named cypress_example with the tag v1 to a Docker registry under the account username (anshita1012).
This might take time if you are running it for the first time.
After the Docker image is built and pushed. The final step is to run the Docker image using the command:
docker run <image_name>:<tag_name>
For example:
docker run cypress_example:v1
As shown above, it is running the tests on a cloud platform using the Dockerfile. You can verify the Cypress test run on the LambdaTest cloud platform (as shown in the screenshot below):
So, following the above approach, you can run your Cypress tests on the cloud platform using Dockerfile on different browsers like Chrome and Firefox.
It is important to note once you have pushed your Docker image, any changes made afterward to the script will not be reflected in the image. To update the image with the latest changes, you must rebuild the image and push it again. Therefore, it is necessary to rebuild and push the Docker image each time you make changes to the script.
GitHub Actions is a powerful CI/CD platform that enables you to automate workflows for building, testing, and publishing software across multiple platforms, operating systems, and programming languages. With GitHub Actions, you can even see the status checks displayed within the pull request.
One of the significant advantages of using Cypress with GitHub Actions is that it allows you to execute Cypress tests in a Docker container, providing a self-contained and repeatable environment for testing.
Fortunately, there is an existing Docker image that already includes Chrome version 87 and Firefox version 82 pre-installed, which you can use to run Cypress tests. To leverage this image, you can pass the container image as an argument. Once the test cases are executed, the container is automatically stopped.
Below is a sample code to run Cypress tests in a Docker container using GitHub Actions:
name: Cypress Test in custom container
on: [push]
jobs:
cypress-test:
runs-on: ubuntu-22.04
name: Cypress Tests on docker container
# Cypress Docker image with Chrome v78
# and Firefox v70 pre-installed
container: cypress/browsers:node12.18.3-chrome87-ff82
steps:
- uses: actions/checkout@v3
- uses: cypress-io/github-action@v5
with:
browser: chrome
The above code sets up a GitHub Actions workflow that triggers when a push event occurs. It then defines a job named cypress-test that runs on an Ubuntu 20.04 virtual machine.
The job specifies the Docker container image to use for running Cypress tests, which in this case is cypress/browsers:node12.13.0-chrome78-ff70.
The job also includes steps to check out the code repository using the actions/checkout@v3 action and to run Cypress tests using the cypress-io/github-action@v5 action.
The browser parameter is set to Chrome to specify that the tests should be run in the Chrome browser.
When you push your code, GitHub Actions will be executed, and you can view your result from the Actions tab.
Sharing some useful Docker commands.
Command | Explanation |
---|---|
docker build -t <image-name> | Build Docker Image |
docker pull <image-name> | Pull Docker Image |
docker push <image-name>:tag-name | Push Docker Image |
docker run -t <image-name> | Run Docker Image |
docker images | Show all docker images |
docker system prune -a | Stop all containers and delete all the images |
docker kill <container-id> | Kill docker container |
docker run <imag_name> | Start Docker |
docker login | Login In |
docker ps -a | List all running docker containers |
docker stop | Stop container |
docker logs containerId | View the logs |
docker-compose up | Start a group of containers defined in a Docker Compose file. |
If you are a developer or a tester, the Cypress 101 certification from LambdaTest is a great way to learn Cypress and enhance your skills in test automation. It is designed for beginners and experienced developers and testers who want to learn the basics of Cypress and how to use it to write automated tests for web applications.
Docker makes it easy to build and run applications in containers, and Cypress makes it easy to write and execute tests in a browser. By combining these two tools, you can create a powerful testing environment that is reliable and efficient.
In this Cypress Docker tutorial, we have seen how using Cypress tests with Docker provides an efficient and reliable way to write and execute tests in a browser. By creating a Dockerfile with the necessary instructions for building a Docker image, you can easily build and run the image on both Chrome and Firefox browsers. The Docker container can also be easily deployed and scaled, making it a valuable tool for automated testing. With the powerful combination of Docker and Cypress, developers can ensure that their web applications are thoroughly tested and meet the desired quality standards. You can learn more about some tips & tricks through the hub on cypress tips and tricks.
On this page
Author's Profile
Anshita Bhasin
Anshita Bhasin is a Senior QA Automation Engineer with over 9 years of experience in the software industry. Throughout her career, She has gained expertise in a variety of tools and technologies, including Rest Assured, Selenium, and Cypress. Currently, She is working at a PropTech company in Dubai. In addition to her technical expertise, she is also passionate about sharing her insights and experiences with others in the form of tutorials and workshops to help guide those just starting out in their careers or seeking advice on their professional paths. You can also follow her on Twitter.
Reviewer's Profile
Harshit Paul
Harshit is currently the Director of Product Marketing at LambdaTest. His professional experience spans over 7 years, with more than 5 years of experience with LambdaTest as a product specialist and 2 years at Wipro Technologies as a certified Salesforce developer. During his career, he has been actively contributing blogs, webinars as a subject expert around Selenium, browser compatibility, automation testing, DevOps, continuous testing, and more.
Get 100 minutes of automation test minutes FREE!!