Commands in Cypress

In cypress for the automation testing, few commands are used mostly in all the testing programs. Cypress also supports the jQuery commands. The few commands which are repeatedly used in all testing programs are as follows,

  • cy.get()
  • find()
  • cy.wait()
  • cy.pause()
  • click()
  • length()
  • cy.log()
  • cy.reload()
  • clear()
  • type()
  • as()
  • cy.clearCookies()
  • cy.clearLocalStorage()
  • cy.clock(date)
  • cy.viewport()
  • cy.title()

Now let us understand how to use these commands in the programs.

cy.get() and find() commands in cypress

get() command in Cypress

cy.get() is the method to get the web element based on the CSS.

Example program: In the below program .gLFyF is the class name of the search element of Google.

describe(('My First Test suite'),
function() {
  it('My First testcase',
  function() {
    cy.visit("https://www.google.co.in/");
    cy.get('.gLFyf').type('cherchertech');
    //get is a method , to give control to the cypress for a particular web element.
   //type is the operation which types the given sentence or word in the web element.
  })
})

Output: Run the above program in the test runner. The result will be as the below image,

get-command-cypress

find() command in Cypress

find() command is also used to search for the web elements. It is not associated with the prefix cy. To use this command, we have to chain the find() command with the other commands.

find() command is majorly chained with cy.get() command.

The syntax for chaining the find() command with cy.get() :

cy.get(parentSelector).find(childSelector)

Example program :

describe(('My First Test suite'),
    function() {
        it('My First testcase',
            function() {
                cy.visit("https://example.com/");
            })
        it('find chained with get', () => {
            cy.get('div').find('h1')
        })
    })

Output :

find-chained-with-get

We know how to use CSS in the cypress using the commands cy.get() and find().

Implicit wait, pause command in cypress

cy.wait() command

Implicit wait [cy.wait()] command is used in the program to completely load the web page. Some applications or web pages take more time to load than the default time set in cypress.

By using this command we can reset the default time taken to load the web page. It is an optional command. Before proceeding to the next test cases, to avoid the error because of loading, implicit wait is used.

Example program :

describe(('My First Test suite'),
    function() {
        it('My First testcase',
            function() {
                cy.visit("https://example.com/");
            })
        it('should wait for 3 seconds', () => {
            //implicit wait
            cy.wait(3000)
        })
        it('should check for correct elements on the page', () => {
            cy.get('h1').should('be.visible')
        })
    })

Output :

wait-implicit-command

The pause method is used to stop the testing temporarily. It is mainly used for easier debugging purposes.

Example program :

describe(('My First Test suite'),
    function() {
        it('My First testcase',
            function() {
                cy.visit("https://example.com/");
            })
        it('should pause the execution', () => {
            cy.pause()
        })
        it('should check for correct elements on the page', () => {
            cy.get('h1').should('be.visible')
        })
    })

Output :

pause-command

Interacting with elements in cypress

click() command

The click() method is used to select the icon or a specific topic on the web page in cypress. Let us understand this method with an example program.

With the help of a program, let us visit the https://chercher.tech/ web page. In the Testing topic, the article named Automation Anywhere is opened.

file-to-click

Example program: The Below program opens the specific article named Automation Anywhere in the chercher.tech website.

describe(('My First Test suite'),
    function() {
        it('My First testcase',
            function() {
                cy.visit("https://chercher.tech/");
                cy.url().should('include', 'chercher.tech')
            })
        it('should click the more information', () => {
            cy.get('.plan').contains('Automation Anywhere').click()
            //.plan is the CSS using class name of the Testing topic
        })
    })

Output: An error has occurred in the output. The program is completely correct but the test cases get failed because when cypress selects the topic Automation Anywhere, it directs to a different URL.

click-error-output

To overcome the above error the program is modified accordingly as below.

Example program :

describe(('My First Test suite'),
    function() {
        it('My First testcase',
            function() {
                cy.visit("https://chercher.tech/");
                cy.url().should('include', 'chercher.tech')
            })
        it('should click the more information', () => {
            cy.get('.plan').contains('Automation Anywhere').click()
        })
        Cypress.on('uncaught:exception', (err, runnable) => {
            // returning false here prevents Cypress from failing the test
            return false
        })
    })

Output :

error-rectification-click-method

click() to select the invisible elements

Only on moving the mouse at the Sub Menu[Hover On Me], the options are displayed in the below image when we visit the page https://chercher.tech/practice/popups.Which means that the options are invisible.

Inorder to select the options without hovering the mouse at the Sub Menu[Hover On Me], we can select the options by passing {force:true}in the click() command as click({force:true})

hidden-options-cypress

Example program :

describe("select box", () => {
  it("should load website with selectbox", () => {
    Cypress.on("uncaught:exception", (err, runnable) => {
      // returning false here prevents Cypress from
      // failing the test
      return false;
    });
    cy.visit("https://chercher.tech/practice/popups");
    cy.contains("CherCher Tech").click({ force: true });
    cy.url().should("include", "chercher.tech");
  });
});

Output :

clicking-invisible-elements-cypress

Validating the number of elements

length() command

A program can be validated according to the number of elements on the web page. Let us understand the length() command with an example.

In the chercher.tech web site there are six main topics namely

  • TESTING
  • DEVELOPMENT
  • CERTIFICATIONS A TO C
  • CERTIFICATIONS D TO O
  • CERTIFICATIONS I TO Z
  • FORUMS

The length of the web site is six because in a common header named chercher.tech there are six sub-topics. For each sub-topics, the length differs.

Example program :

describe(('My First Test suite'),
    function() {
        it('My First testcase',
            function() {
                cy.visit("https://chercher.tech/");
                cy.url().should('include', 'chercher.tech')
            })
        it('display correct number of elements', () => {
            cy.get('.plan').its('length').should('eq', 6)
        })
    })

Output :

validating-count-of-elements-length-method

The trick for easier debugging in cypress

cy.log() command

cy.log() command is used in the test programs for easier the debugging. In the output, we can analyze what each test case does. Basically, instead of giving comments in the program, we are giving the comments in the output using this command.

For example, When a client views your test program for the first time, it will be easier for them to understand the program flow while executing.

Example program :

describe(('My First Test suite'),
    function() {
        it('My First testcase',
            function() {
                cy.visit("https://chercher.tech/");
                cy.url().should('include', 'chercher.tech')
                cy.log('website loaded!!')
            })
        it('display correct number of elements', () => {
            cy.get('.plan').its('length').should('eq', 6)
        })
    })

Output :

log-command

cy.reload() command

It is used to reload the webpage to avoid errors. While performing a sequence of tests, cy.reload() command is used.

Example program :

describe("My First Test suite", function () {
  it("My First testcase", function () {
    cy.visit("https://chercher.tech/");
    cy.url().should("include", "chercher.tech");
    cy.log("Before reload");
    cy.reload();
    cy.log("after reload!");
  });
});

Output :

reload-method

Interacting using the inputs on the webpage

Now let us learn how to interact with the elements and how to automate the checkboxes on the web page using the below commands

  • cy.visit() method is used to visit or load a particular page
  • cy.get() method is used to get the web page element of the given CSS
  • cy.contains() method is used to check whether the given string is present or not on the web page.
  • click() command clicks or selects the elements for the given CSS.
  • clear() method is used to erase the already typed string in the given element.
  • type() method is used to type the given string in the web element. In this method, we can also slow down the typing speed bypassing the arguments as
cy.get('#user_login').type('invalid name'),{delay : 50}‚Äč

Example program :

describe('working with inputs', function () {
  it('should load login page', function () {
    cy.visit('http://zero.webappsecurity.com/login.html');
    //visits the page
  });
  it('should fill username', function () {
    cy.get('#user_login').clear();
    //get the box for username and makes the box empty
    cy.get('#user_login').type('invalid name');
    //get the box for username and type the string-invalid name
  });
  it('should fill password', function () {
    cy.get('#user_password').clear();
    //get the box for password and makes the box empty
    cy.get('#user_password').type('invalid password');
    //get the box for password and type the string-invalid password
  });
  it('should select checkbox', function () {
    cy.get('input[type="checkbox"]').click();
    //selects the checkbox-keep me signed in
  });
  it('should fill login form', function () {
    cy.contains('Sign in').click();
    //selects the sign in only is the web page contains the string sign in
  });
  it('should display error message', function () {
    cy.get('.alert-error').should('be.visible');
    //gets the error message if it is visible
  });
});

Output :

interaction-using-inputs

Aliases in cypress

as() command

Aliasing is like declaring the variables. But in cypress declaring variables is not supported but it is possible with the help of promises which we will discuss in the forthcoming articles.

Sometimes the CSS of the element has alphanumeric characters. In that case, we get confused about for what element the selector is used. To make the program much more readable aliases are used using the command as().

Instead of the CSS, by using the aliased name we can execute the program.

Example program :

describe('working with inputs', function () {
  it('should load login page', function () {
    cy.visit('http://zero.webappsecurity.com/login.html');
    //visits the page
  });
  it('should fill username', function () {
    cy.get('#user_login').as('username');
    //alias for the CSS of the username element
    cy.get('@username').clear();
    //@username is the another name/the alias name used for the CSS #user_login
    //get the box of username and makes the box empty
    cy.get('@username').type('invalid name');
    //get the box for username and type the string-invalid name
  });
  it('should fill password', function () {
    cy.get('#user_password').as('password');
    //alias for the CSS of the password element
    cy.get('@password').clear();
    //@password is the another name/the alias name used for the CSS #user_password
    //get the box of password and makes the box empty
    cy.get('@password').type('invalid password');
    //get the box for password and type the string-invalid password
  });
});

Output :

alias-output

Clearing cookies and Local storage in cypress

cy.clearCookies() and cy.clearLocalStorage() command

Cypress automatically clears the cookies and local storage before performing each test. In order to clear specific cookies or storage in a test, cy.clearCookies() and cy.clearLocalStorage() command is used respectively.

Example program :

describe('clearing cookies and storage', function () {
  it('should load login page', function () {
    cy.visit('http://zero.webappsecurity.com/login.html');
    //visits the page
    cy.clearCookies({log: true});
    //clears cookies specifically in this test case
    cy.clearLocalStorage('your item', {log: true});
    //clears the local storage specifically in this test case
    //It is suggested to include the log value as true to enhance the test result.
  });

Output :

clear-cookies-localstorage-output

Date and time modification in cypress

cy.clock() command

To override the time using cy.clock(), we have to create an object for date. This command can be used in any type of testing platform. Let us learn how to override the time in the testing program with a simple example.

Example program :

describe('clearing cookies and storage', function () {
  it('override the current time', function () {
    const date = new Date(2020, 9, 2).getTime();//object creation
    //return a timestamp i.e retuns the time at which the test occured
    cy.clock(date);
    cy.log(date);
    cy.visit('http://zero.webappsecurity.com/login.html');
  });
});

Output :

overriding-date-time

Modifying the viewport in cypress

cy.viewport() command

By using this command you can run the tests in multiple devices and different types of screens in cypress.

Example program : The below program is given when we visit a webpage but on different screens.

describe('Deviec Tests', function () {
  it('different screens', () => {
    cy.visit('http://www.example.com');
    cy.viewport(1280, 720);
    //by giving the height and width
    cy.wait(3000);
    cy.viewport('iphone-x');
    //by giving model name
    cy.wait(3000);
    cy.viewport('ipad-mini');
    //by giving model name
    cy.wait(3000);
  });
});

Output: In the below image we can see how the screen modifies accordingly to the specified criteria.

different-screen-output

Get and assert page titles in Cypress

cy.title() command

This command is used to grab the CSS of the title of the web page which is currently active.

Example program :

describe('Title', function () {
  it('different screens', () => {
    cy.visit('http://www.example.com');
    cy.title().should('include', 'Example Domain');
  });
});

Output :

title-assertion

These are the few commands which are repeatedly used in any test programs. Now, We have completed the basic concepts of the Cypress. Now let us learn advanced concepts of cypress in the forthcoming articles.

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions