If you don’t include tests in your Drupal development, chances are it’s because you think it adds complexity and expense without benefit. Cypress is an open source tool with many benefits:
- Reliably tests anything that runs in a web browser
- Works on any web platform (it’s great for testing projects using front-end technologies like React)
- Highly extensible
- Increasingly popular
- Easy to learn and implement
- Protects against regression as your projects become more complex
- Can make your development process more efficient
This article covers three topics to help you start testing your Drupal project using Cypress:
- Installing Cypress
- Writing and running basic tests using Cypress
- Customizing Cypress for Drupal
Install Cypress
For the purposes of this tutorial I’m assuming that you have built a local dev environment for your Drupal project using the `drupal/recommended-project` project. Although details on creating such a project are outside of the scope of this piece, I recommend Getting Started with Lando and Drupal 9.
Your project has at least this basic structure:
vendor/
web/
.editorconfig
.gitattributes
composer.json
composer.lock
The cypress.io site has complete installation instructions for various environments. For this article, I installed Cypress using npm.
Initialize your project using the command npm init
. Answer the questions that Node.js asks you, and then you will have a package.json
file that looks something like this:
{
"name": "cypress",
"version": "1.0.0",
"description": "Installs Cypress in a test project.",
"main": "index.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"author": "",
"license": "ISC"
}
Install Cypress in your project:
$ npm install cypress --save-dev
Run Cypress for the first time:
$ npx cypress open
Because you haven’t added a config or any scaffolding files to Cypress, the Cypress app displays the welcome screen to help you configure the project. To configure your project for E2E (end-to-end) testing, click the Not Configured button for E2E Testing. Cypress adds some files to your project:
cypress/
node_modules/
vendor/
web/
.editorconfig
.gitattributes
composer.json
composer.lock
cypress.config.js
package-lock.json
package.json
Click Continue and choose your preferred browser for testing. Click Start E2E Testing in [your browser of choice]. I’m using a Chromium-based browser for this article.
In a separate window, a browser opens to the Create your first spec page:
Cypress Testing for Drupal Websites webinar, particularly the section on fixtures that begins at 18:33. That webinar goes into greater detail about some interesting use cases, including an Ajax-enabled form. Once you start using it, feel free to use or fork Aten’s public repository of Cypress Testing for Drupal.
Happy testing!
This article originally appeared on the Aten blog and is republished with permission.