Open In App

Variables in Cypress

Last Updated : 04 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Cypress is a front-end testing tool. It allows us developers and QA engineers who build web applications using the modern JavaScript framework to set up, write, run, and debug tests. It is getting popular as it enables us to write faster, easier, and more reliable tests. Cypress can test anything that runs in a browser.

Let's learn about the most basic component - variables in Cypress.

Types of Variables

Variables are containers for storing information.

  • Variables are used to store and manage data.
  • We can create a variable or rather declare a variable in JavaScript syntax for Cypress.
  • In Crypress, we use objects while using closures which can be utilized without assigning them.
  • However, when we need to deal with mutable objects, we use variables. Variables allow us to compare an object's previous value to the next value. Variables are mutable types in JavaScript, which means that the value that is stored in the variable (a container) can be changed (set, removed, or modified).

Rules for naming variables

The rules for naming variables for Cypress are the same as the rules for naming variables in JavaScript as Cypress is purely based on JavaScript. So following are the rules for naming variables:

  1. Variable names must start with a letter, an underscore(_), or a dollar sign($).
  2. Variable names can contain numbers, alphabets, underscores(_) and dollar sign($).
  3. Variable names cannot contain spaces.
  4. Special characters and symbols are not allowed in variable names.
  5. By convention, variable names in JavaScript are written in camelCase.
  6. Variable names cannot be a reserved keyword.
  7. Variable names should be short and descriptive to make it easy and efficient to understand.
  8. In JavaScript, variables do not have a set data type, (like int or integer, bool or boolean, or string and so on) .

Types of Variables

There are three types of variables:

  • var
  • let
  • const

1. var

The var keyword is used to declare a variable. It has the following scope behaviors- function-scoped and global-scoped.

Syntax

var variable_name = assign_some_value ;

Example

var age = 20 ;

Code ( basic usage of var keyword)

JavaScript
var a = "Hello Geeks!"
var b = 5;
var c = 10;
var addition = b + c ;
console.log(a);
console.log(addition);

Output

Hello Geeks!
15

2. let

The let keyword is also used to declare a variable. It has block-scoped behavior. It is used for variables whose values may change.

Syntax

let variable_name = assign_some_value ;

Example

let fruit = "ripe" ;

Code ( basic usage of var keyword)

JavaScript
let a = "Hello Geeks!"
let b = 5;
let c = 10;
let addition = b + c ;
console.log(a);
console.log(addition);

Output

Hello Geeks!
15

3. const

The const keyword is also used to declare a variable, however, it is used for declaring variables that cannot be reassigned. It has the following scope behaviors- function-scoped and global-scoped. It is used for variables whose values should not change.

Syntax

const variable_name = assign_some_value ;

Example

const pi = 3.14 ;

Code ( basic usage of var keyword)

JavaScript
const a = "Hello Geeks!"
const pi = 3.14;
const radius = 10;
const circumference = 2 * pi * radius ;
console.log(a);
console.log(circumference);
// If you change value of radius variable
// It will show error
// Because cannot change value of const variables

Output

Hello Geeks!
62.800000000000004

Code Implementation of variables in Cypress

Example - A simple counter application

In below code we have 2 files, one for html and one for JavaScript.

  • The HTML file provides a button to increment a counter.
  • The JavaScript files (2 versions are provided to you to try and test on Cypress) has code to ensure that each test starts with a fresh page load of index.html. It has a variable num1 that captures initial count value and stores value.
  • The cy.get finds the counter element and retrieves its text content which is used to initialize num1.
  • The click even simulates a click on the increment button. After clicking the button, it it retrieves the updated count num2 and asserts that it equals num1+1 to ensure that the count is incremented correctly.

HTML (index.html)

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Counter App</title>
</head>
<body>
  <button id="incrementBtn">Increment</button>
  <span data-testid="counter">0</span> times clicked
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function() {
      let count = 0;
      $('#incrementBtn').on('click', function() {
        $('[data-testid="counter"]').text(++count + ' times clicked');
      });
    });
  </script>
</body>
</html>

JavaScript - Cypress Test (counter_spec.js)

JavaScript
describe('Counter App', () => {
  beforeEach(() => {
    cy.visit('index.html'); // Assuming index.html is in the root of your project
  });

  it('increments the counter correctly', () => {
    // Using var (though not recommended in modern JS, just for demonstration)
    cy.get('[data-testid="counter"]').then(function($span) {
      var num1 = parseInt($span.text(), 10); // Using parseInt for clarity

      cy.get('#incrementBtn').click();

      cy.get('[data-testid="counter"]').then(function($span) {
        var num2 = parseInt($span.text(), 10);

        expect(num2).to.equal(num1 + 1);
      });
    });

    // Using let (modern recommended approach)
    cy.get('[data-testid="counter"]').then(($span) => {
      let num1 = parseInt($span.text(), 10);

      cy.get('#incrementBtn').click();

      cy.get('[data-testid="counter"]').then(($span) => {
        let num2 = parseInt($span.text(), 10);

        expect(num2).to.equal(num1 + 1);
      });
    });

    // Using const (for the immutable reference to DOM element)
    cy.get('[data-testid="counter"]').then(($span) => {
      const num1 = parseInt($span.text(), 10);

      cy.get('#incrementBtn').click();

      cy.get('[data-testid="counter"]').then(($span) => {
        const num2 = parseInt($span.text(), 10);

        expect(num2).to.equal(num1 + 1);
      });
    });
  });
});
JavaScript
describe('Counter App', () => {
  beforeEach(() => {
    cy.visit('index.html'); // Assuming index.html is in the root of your project
  });

  it('increments the counter correctly', () => {
    // Using let and const variables 
    // Capture initial count
    let num1;
    cy.get('[data-testid="counter"]').then(($span) => {
      num1 = parseInt($span.text(), 10);

      // Click the button to increment
      cy.get('#incrementBtn').click();

      // Verify the updated count
      cy.get('[data-testid="counter"]').then(($span) => {
        const num2 = parseInt($span.text(), 10);

        // Assert that the count increased by 1
        expect(num2).to.equal(num1 + 1);
      });
    });
  });
});

Conclusion

One needs to be proficient in JavaScript before getting started with Cypress Testing. This is due to the fact that Cypress is purely based on JavaScript and this tool is designed to meet the needs of front-end developers in particular. So, we have covered one of the basic topics, variables, in this article.


Next Article

Similar Reads