Handling Child Windows with Cypress

CypressTest AutomationSoftware Testing

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

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 window and it provides the workaround to continue our tasks on the parent window itself. At first the href attribute from the html code is grabbed. This is done with the help JQuery method prop() [ this shall give the value of the property passed as an argument to the method].

Now after the value of the href property is obtained, we can launch the url with the help of visit() command in Cypress. However the test gets successful only if the other application should have the same domain as the original application [a different sub domain of the two applications is accepted].

Cypress takes it as a security threat if we are to access another application in the same window with the help of visit() command. Thus we cannot work with more than one domain at a time.

Example

Code Implementation to handle child windows.

describe('Tutorialspoint Test', function () {
   // test case
   it('Test Case6', function (){
      // launch the application
      cy.visit("https://accounts.google.com/signup");
      // grab the href prop with prop() JQuery method
      cy.get(':nth-child(1) > a').then(function(l){
         const txt = l.prop('href');
         // get the url in logs
         cy.log(txt);
         // launch the url again
         cy.visit(txt);
      })
   });
});

Test runner logs is as shown below −


raja
Published on 05-Aug-2020 12:17:01
Advertisements