Handling Child Tabs with Cypress


Sometimes on clicking a link or button, it opens to another tab in the same browser. Cypress has a unique way of handling child tabs unlike other automation tools like Selenium and Protractor. It basically keeps no information on the child tab by shifting its focus from the parent to the child tab.

Now let us understand why a link or a button opens a new webpage on a different tab considered as a child. This is due to the attribute target set in the html for that element. If omitted, it shall open in the same window.

Cypress cannot directly handle a child tab and it provides the workaround to continue our tasks on the parent tab itself by deleting the target attribute from the html code. This is done with the help of invoke() command in Cypress which invokes the JQuery function removeAttr() [ this shall delete the attribute passed as an argument to the function].

Now clicking on the link or button, it shall open on the parent tab itself and we shall perform the necessary actions and validations there. Finally move back to the previous URL in browser history with the go() Cypress command.

The go() method is used to move backward and forward to the previous or next URL respectively in the browser history. We can also specify numbers as arguments to the go(). [-1 to moves back a page and 1 to move forward a page]

Syntax

cy.go(direction), cy.go('back')

There can be of two types of options as listed below which can modify the default behavior of go() method −

  • log − The default value of log is true.

  • timeout − The default value of timeout parameter is pageLoadTimeout (60000 milliseconds). This the duration to wait for cy.go() to complete its loading event.

Example

Code Implementation to handle child tab.

describe('Tutorialspoint Test', function () {
   // test case
   it('Test Case4', function (){
      // launch the url
      cy.visit("https://www.tutorialspoint.com/selenium /selenium_automation_practice.htm");
      // removing the target attribute from the link with removeAttr()
      cy.get('a[title="TutorialsPoint - Home"]')
      .invoke('removeAttr', 'target').click();
      // assertion to verify the current Url
      cy.url().should('include','https://www.tutorialspoint.com/index.htm');
      // moving back to the parent tab with the help of go() method
      cy.go('back');
   });
});

Finally we can use the assertion to validate that we have moved to the correct URL by cy.url().

Updated on: 05-Aug-2020

910 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements