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:
- Variable names must start with a letter, an underscore(_), or a dollar sign($).
- Variable names can contain numbers, alphabets, underscores(_) and dollar sign($).
- Variable names cannot contain spaces.
- Special characters and symbols are not allowed in variable names.
- By convention, variable names in JavaScript are written in camelCase.
- Variable names cannot be a reserved keyword.
- Variable names should be short and descriptive to make it easy and efficient to understand.
- 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:
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.
Similar Reads
CSS Variables
CSS variables (custom properties) are reusable values defined with two dashes (--) that make your CSS code efficient and easier to maintain. Store values like colors, sizes, or fonts in one place for centralized updates.Use var() to apply these variables anywhere in your CSS.Improve code readability
3 min read
Environment Variables in Cypress
Cypress is a modern front-end test instrument. One can write strong, reliable end-to-end tests using Cypress which should ensure that applications are running smoothly and securely. A vital aspect of the flexibility and maintainability of Cypress tests lies in its utilization of environment variable
11 min read
Reports in Cypress
Cypress is an open-source website testing tool that is used to automate tests for JavaScript web applications. It is designed for end-to-end testing and it can be used for unit tests and integration tests as well. It is fast, reliable, and can run in real-time directly in the browser. It's built to
5 min read
Variables in COBOL
Declaring and initializing variables might be simple for programmers. However, if this is your first programming language, think of a variable as a container in which you can fill an unknown quantity â a value of said data type. Based on its use, this variable's value is then stored at a particular
8 min read
ES6 | Variables
A variable is a named container in the memory, that stores the values. In simple words, we can say that a variable is a container for values in Javascript. The ES6 Variable names are called identifiers. The rules to keep in mind while naming an identifier. An identifier can contain alphabets and num
4 min read
Perl | Variables
Variables in Perl are used to store and manipulate data throughout the program. When a variable is created it occupies memory space. The data type of a variable helps the interpreter to allocate memory and decide what to be stored in the reserved memory. Therefore, variables can store integers, deci
4 min read
Less.js Variables
LESS (Leaner Style Sheets) is a simple CSS pre-processor that facilitates the creation of manageable, customizable, and reusable style sheets for websites. It is a dynamic style sheet language that enhances the working power of CSS. LESS supports cross-browser compatibility. CSS pre-processor is a s
4 min read
Cypress - Web Tables
One thing that matters a lot in the field of web development is how reliable and functional the web applications are. One of these tools, Cypress, being flexible has really contributed to end-to-end testing by offering strong ways for automating tests. Cypress can validate, process and manipulate we
7 min read
Less.js Variables Overview
The Variables in LESS.js govern the common values used in a single location, ie, they are known to keep values stored in them and can be used anywhere within the definition of code. LESS allows you to use these variables to change the specific value in the entire code. It might get troublesome when
2 min read
Variables in LISP
Similar to other languages, in LISP variables are named places that store a particular value, but they are not declared the way you declare variables in C++ or Java i.e you don't need to mention data-type of variables when declaring them as LISP is dynamically typed. LISP supports two types of varia
3 min read