More

    Effortlessly Test Your Drupal Website with Cypress

    Enhancing Drupal Development with Cypress Testing

    If you don’t include tests in your Drupal development, chances are it’s because you think it adds complexity and expense without benefit. However, testing is a crucial component of robust software development, especially as projects grow in size and complexity. Enter Cypress, an open-source testing tool that streamlines this process while providing an array of benefits that can elevate your development workflow.

    Why Choose Cypress for Testing?

    Cypress is increasingly popular in the development community for several compelling reasons:

    • Reliable Testing: It can test anything that runs in a web browser, making it versatile for various web applications.
    • Cross-Platform Compatibility: Cypress works seamlessly across different web technologies, including popular frameworks like React.
    • Extensibility: The tool is highly extensible, allowing for customization based on specific project needs.
    • Ease of Learning: Developers find it easy to learn and implement, which reduces the barrier for integrating automated tests into existing workflows.
    • Regression Prevention: As your projects become more complex, Cypress helps protect against regression, ensuring that new changes don’t break existing functionality.
    • Efficiency Boost: Implementing Cypress can make your entire development process more efficient, saving time in the long run.

    Getting Started: Three Key Areas

    This article focuses on three main topics to help you get started testing your Drupal project using Cypress:

    1. Installing Cypress
    2. Writing and Running Basic Tests
    3. Customizing Cypress for Drupal

    Installing Cypress

    For this tutorial, it’s assumed you have a local development environment set up for your Drupal project using the drupal/recommended-project. If you’re unsure how to create this project, I recommend checking out Getting Started with Lando and Drupal 9.

    Your project should have at least this basic structure:

    bash
    vendor/
    web/
    .editorconfig
    .gitattributes
    composer.json
    composer.lock

    Cypress offers complete installation instructions for various environments. In this guide, we’ll install Cypress using npm:

    1. Initialize your project with the command:
      bash
      npm init

      Answer the questions Node.js prompts you with. This will create a package.json file.

    2. Install Cypress as a development dependency:
      bash
      npm install cypress –save-dev

    3. Launch Cypress for the first time:
      bash
      npx cypress open

    Upon running this command, the Cypress app opens, displaying a welcome screen to help configure your project. For end-to-end (E2E) testing, click Not Configured to allow Cypress to set up the necessary scaffold, adding several files to your project.

    You will also define the browser of choice for testing, initiating the testing environment in a separate window with the Create your first spec page.

    Click on Scaffold example specs to create example specifications that guide you on using Cypress effectively. These examples illustrate an intuitive JavaScript-based language, allowing easier comprehension and implementation.

    Writing and Running Basic Tests with Cypress

    Next, create a new directory named integration within the /cypress folder. Inside the integration folder, create a file titled test.cy.js:

    bash
    cypress/
    ├─ e2e/
    ├─ fixtures/
    ├─ integration/
    │ ├─ test.cy.js
    ├─ support/
    node_modules/
    vendor/
    web/
    .editorconfig
    .gitattributes
    composer.json
    composer.lock
    cypress.config.js
    package-lock.json
    package.json

    Populate your test.cy.js file with the following example code:

    javascript
    describe(‘Loads the front page’, () => {
    it(‘Loads the front page’, () => {
    cy.visit(‘/’)
    cy.get(‘h1.page-title’).should(‘exist’);
    });
    });

    describe(‘Tests logging in using an incorrect password’, () => {
    it(‘Fails authentication using incorrect login credentials’, () => {
    cy.visit(‘/user/login’)
    cy.get(‘#edit-name’).type(‘Sir Lancelot of Camelot’);
    cy.get(‘#edit-pass’).type(‘tacos’);
    cy.get(‘input#edit-submit’).contains(‘Log in’).click();
    cy.contains(‘Unrecognized username or password.’);
    });
    });

    Click on the test.cy.js file within the Cypress application to observe the tests being executed in real-time. The dynamic panels display each step as Cypress navigates through the specs. This setup not only tests your site’s functionality but also highlights potential issues—such as needing to ensure a clickable submit button is visible.

    Customizing Cypress for Drupal

    You can extend Cypress’s capabilities by creating custom commands tailored to your Drupal application. Recall the supportFile entry in your cypress.config.js, which points to a file where you can import these custom commands.

    Here’s how you can define commands in the commands.js file:

    javascript
    /**

    • Logs out the user.
      */
      Cypress.Commands.add(‘drupalLogout’, () => {
      cy.visit(‘/user/logout’);
      });

    /**

    • Basic user login command. Requires valid username and password.
    • @param {string} username
    • The username with which to log in.
    • @param {string} password
    • The password for the user’s account.
      */
      Cypress.Commands.add(‘loginAs’, (username, password) => {
      cy.drupalLogout();
      cy.visit(‘/user/login’);
      cy.get(‘#edit-name’).type(username);
      cy.get(‘#edit-pass’).type(password, { log: false });
      cy.get(‘#edit-submit’).contains(‘Log in’).click();
      });

    With these commands, you can log out users and log in with any specified username and password. Additionally, you can script a custom Cypress command called drush(), allowing you to run Drush commands directly within your tests, such as:

    javascript
    /**

    • Logs a user in by their uid via drush uli.
      */
      Cypress.Commands.add(‘loginUserByUid’, (uid) => {
      cy.drush(‘user-login’, [], { uid, uri: Cypress.env(‘baseUrl’) })
      .its(‘stdout’)
      .then(function (url) {
      cy.visit(url);
      });
      });

    This command enhances security by avoiding the need to store user passwords in your tests. The ability for Cypress to execute Drush commands—a primarily back-end tool—transforms how you interact with your Drupal applications.

    Explore Further

    Cypress capabilities extend beyond simple examples to include fixtures for test data, nuanced navigation techniques, and complex UI interactions. For a deeper dive into advanced features, consider watching the Cypress Testing for Drupal Websites webinar, particularly the section on fixtures starting at 18:33.

    Feel free to explore or fork Aten’s public repository of Cypress Testing for Drupal for additional insights into utilizing Cypress effectively in your own projects.

    Happy testing!

    Latest articles

    Related articles

    Leave a reply

    Please enter your comment!
    Please enter your name here

    Popular