
GuideE2E Testing with GatsbyJS: 5 Steps to Enable End-to-End Testing for Deploy Previews with Github Actions
Introduction
End-to-End (e2e) testing is a crucial aspect of the software development process. It allows us to verify that our applications are functioning correctly from start to finish.
By incorporating e2e testing, we can ensure that visual elements are working as expected and that users have a seamless experience across different environments.
In this guide, we will focus on utilizing Cypress for e2e testing with a Gatsby application, hosted on Netlify.
To proceed with the setup and configuration of our e2e testing environment using Cypress, Netlify, and Gatsby, please ensure that you have the following prerequisites in place:
Basic knowledge of JavaScript.
A Netlify account.
Node.js and npm installed on your machine.
Motivation
Our motivation for creating this guide is two-fold. Firstly, we aim to provide developers with an easy-to-understand and comprehensive resource for integrating e2e testing with Cypress. By following this guide, you will be able to efficiently incorporate e2e testing into your project.
Secondly, we recognize the numerous benefits that e2e testing brings to businesses, and how important it is to have these pipelines running as soon as possible.
With these motivations in mind, we are delighted to share a simple and extendable approach to integrate e2e testing with Gatsby and Netlify the easy way.
Creating a new Gatsby project
To begin, we need to create a new Gatsby project from scratch. We will be using one of the available starters to set up our project quickly.
Follow these steps:
Open your terminal and execute the following command: npx gatsby new gatsby-cypress-e2e https://github.com/gatsbyjs/gatsby-starter-hello-world
This command will create a new folder called gatsby-cypress-e2e and generate a Gatsby project based on the hello-world starter.
Navigate into the newly created directory by running the following command: cd gatsby-cypress-e2e
Start the Gatsby development server with the following command: npx gatsby develop
Wait until you see a message indicating that your project is available at localhost:8000. This means that your Gatsby project is up and running.
Now that we have successfully created a new Gatsby project, let's move on to the next section to integrate Cypress into our project.
Add Cypress into our project
In this section, we will integrate Cypress into our Gatsby project. Cypress is a powerful tool that allows you to create tests for modern web applications, debug them visually, and automate their execution in your continuous integration builds.
To get started, follow these steps:
Open the terminal at the root of your Gatsby project.
Execute the following command to install Cypress as a development dependency: npm install cypress --save-dev
This command will add Cypress to your project's dependencies, allowing you to utilize its testing capabilities.
Now that Cypress is successfully installed in our project, we can move on to the next section to configure Cypress integration with Gatsby.
Executing Cypress
Now that we have integrated Cypress into our Gatsby project, let's open Cypress and verify that our installation was successful.
To open Cypress, follow these steps:
Open your project terminal at the root of your Gatsby project.
Execute the following command: npx cypress open
This command will launch Cypress for the first time and set up the necessary files and folders.
Note: If you are using Linux and encounter an error message regarding missing dependencies, please refer to the Cypress documentation for Linux prerequisites and install the required dependencies based on your distribution.
Once the command runs successfully, Cypress should open, and you should see the Cypress Test Runner interface.
Adding our test
Now, let's implement our e2e test. In this case, we will create a basic assertion that verifies the presence of the text "Hello World" on our page.
Follow these steps to add the test:
Open the cypress/e2e folder in your project. If the folder doesn't exist, create it.
Inside the e2e folder, create a new file called home.cy.js and add the following code:
1describe("Home component", () => {
2 beforeEach(() => {
3 cy.visit("/") // Visit the home page
4 })
5
6 it('should display "Hello world!"', () => {
7 cy.get("div").contains("Hello world!").should("exist") // Ensure that the text exists within the div
8 })
9})Explanation of the code above:
The describe block sets the context for our test suite, which in this case is the "Home component".
The beforeEach block specifies that before each test, we should visit the home page.
The it block defines our test case, which verifies that the text "Hello World" exists within a divelement.
Create a new file called cypress.config.js at the root of your project. Add the following code:
1module.exports = {
2 e2e: {
3 baseUrl: "http://localhost:8000",
4 },
5}This configuration file sets the base URL for Cypress, which in our case is http://localhost:8000where the Gatsby development server runs.
Make sure to save the file.
Now, with the Gatsby development server running, open Cypress once again by running the command npx cypress open in your project terminal.
Once the Cypress window opens, select "electron" as the browser and click on the listed test that we just created.
The test will start running, and you should see a success message indicating that the test passed.
What we have accomplished so far
So far, we have achieved the following:
Created a basic Gatsby project and integrated Cypress as our test suite.
Verified that our Cypress setup is working by running a basic e2e test on the home page.
Configured a base URL for Cypress in the cypress.config.js file.
Successfully executed our test using the Cypress Test Runner.
In the next section, we will explore how to deploy our Gatsby project using Netlify.
Additionally, we will configure Cypress to run in the cloud for every deploy preview using the netlify-plugin-cypressplugin. This will allow us to have our e2e tests automatically executed on each deploy preview, providing further confidence in the stability and functionality of our application.
Let's proceed to the next section to continue with the deployment and configuration process.
Uploading our project into Netlify
In this section, we will upload our Gatsby project to Netlify, a popular hosting platform for static websites.
Follow these steps to upload your project into Netlify:
Create a new repository on GitHub for your project. Make sure not to initialize the repository with a README, license, or .gitignore file. You can add these files later after pushing your project to GitHub.
Push your local repository to GitHub by following the steps provided by GitHub for uploading an existing local repository. This will make your project accessible on GitHub.
Login to your Netlify dashboard.
Click on "New site from Git" or "New site" and select the git provider (GitHub) where you have your repository.
Follow the Netlify setup wizard, leaving everything as default. Netlify will automatically detect that your project is a Gatsby project and set everything up correctly for you.
Wait for Netlify to successfully deploy your site. Once the deployment is complete, you will be assigned a unique URL for your site. Visit the URL and check that everything is working as expected.
Executing our tests on each successful deployment
To execute our tests directly in Netlify, we will use the official Cypress integration for Netlify. This allows us to access the current state of the just-deployed code and catch any errors early.
Follow these steps to configure Cypress to run on each successful deployment:
Go to your project's root folder in the terminal.
Execute the following command to install the official Cypress plugin for Netlify: npm install --save-dev netlify-plugin-cypress
Next, we need to let Netlify know that we want to include this plugin in our deployment pipeline. Create a new file called netlify.toml at the root of your project and add the following code:
1[build]
2
3 [build.environment]
4 # cache Cypress binary in local "node_modules" folder
5 # so Netlify caches it
6 CYPRESS_CACHE_FOLDER = "./node_modules/CypressBinary"
7 # set TERM variable for terminal output
8 TERM = "xterm"
9
10[[plugins]]
11 package = "netlify-plugin-cypress"
12 [plugins.inputs]
13 record = true
14 group = "Testing Built Site"This configuration file specifies the caching of the Cypress binary in the local "node_modules" folder and sets the TERM variable for terminal output. It also includes the netlify-plugin-cypress plugin with additional inputs, such as enabling test recording and specifying the test group "Testing Built Site".
Commit and push your changes to GitHub.
Go to your deploy log in Netlify.
Now, your Cypress tests should be executed right after your deploy preview is available on Netlify.
Next steps
Congratulations on successfully setting up Cypress with Gatsby and Netlify! This integration provides a seamless way to run your e2e tests on each successful deployment.
Here are some next steps you can consider:
Explore additional features: You can extend this setup by integrating the official Cypress Dashboard. The dashboard allows you to store your test results, videos, and even block pull requests if tests are failing. This can further improve the quality and reliability of your application.
Write additional tests: Now that you have a basic test in place, consider adding more tests to cover other important functionality and user flows within your application. Covering edge cases and critical paths can help ensure a robust testing strategy.
Continuously monitor and improve: Make it a practice to review and monitor your tests regularly. Keep an eye on the test results, investigate any failures, and improve or update your tests as needed. This will help maintain the quality and reliability of your application over time.
We hope this guide has been helpful in getting you started with Cypress, Gatsby, and Netlify. If you have any further questions or need assistance, feel free to reach out. Happy testing!