Search This Blog

Tuesday, July 16, 2024

Unlock Web Testing Excellence: Comprehensive Cypress Cheat Sheet !

 Unlock the Full Potential of Cypress with Our Comprehensive Cheat Sheet!

Welcome to my blog! ๐ŸŒŸ If you're a QA engineer or a test automation enthusiast, you're in for a treat. Iโ€™m excited to share an exclusive cheat sheet that dives deep into the world of Cypress, the ultimate tool for modern web testing. This cheat sheet is thoroughly crafted to help you master Cypress and its powerful features effortlessly. Hereโ€™s what youโ€™ll discover inside:


Configurations & Installations
Get started with easy-to-follow setup guides for configuring and installing Cypress in your projects.

Core Concepts Handling

  • Input Box: Learn how to handle text input efficiently.
  • Dropdowns: Navigate and select options with precision.
  • Checkbox: Manage checkboxes seamlessly.
  • iFrames: Master the techniques to interact with embedded iFrames.
  • Windows: Handle multiple browser windows and tabs.
  • Alerts: Manage browser alerts, including prompt alerts requiring text input.
  • Mouse Actions: Execute complex mouse interactions with ease.
  • File Uploading: Automate file upload scenarios flawlessly.

Code Optimization Concepts
Custom Commands: Enhance code reusability with custom commands.
Cypress Fixtures: Manage test data efficiently with fixtures.
Cypress Hooks: Leverage hooks for setup and teardown processes.
Aliases and Variables: Simplify code with aliases and variables.
Custom Utilities: Create utility functions to streamline tests.
Environmental Variables: Handle different environments effortlessly.
Assertions and Retries: Implement robust assertions and retries to make your tests resilient.
Cypress Plugins: Extend Cypress functionality with powerful plugins.

Reporting
- Generate comprehensive test reports to keep track of your testing progress and results.

Screenshots and Videos
- Capture screenshots and videos automatically to help debug failed tests and showcase successful ones.

Dive into this cheat sheet to elevate your Cypress skills and automate web testing like a pro. Whether youโ€™re dealing with core interactions or optimizing your code, this guide has got you covered. Happy testing!

Feel free to share your feedback and experiences in the comments below. Letโ€™s make web testing simpler and more effective together! ๐Ÿš€






































Friday, August 11, 2023

Automation Tools Cross Over


01. Installation 

Selenium:-

* Follow the POM structure with the Maven project

* Install the basic plugins with the Selenium plugin

* Install webdrivermanager plugin


Cypress:-

* npm -i init

* npm install cypress --save --dev


Playwright:-

        * npm init playwright@latest


02. Open Browsers


Selenium:-

public class BrowserOpen {

    public static void main(String args[]){

        WebDriverManager.chromedriver().setup();

        WebDriver driver = new ChromeDriver();

        driver.get("https://www.opencart.com");

        driver.manage().window().maximize();        

    }

}

Cypress:-

<reference type="Cypress" />

it('Attaching Multiple File', () =>{

        cy.visit("https://xxx.xxx.com");

    });


Playwright:-

import {test, expect} from '@playwright/test'

test('Browser Open in Playwright', async({page}) =>{

    await page.goto("https://demo.nopcommerce.com/");

});

03. Alert Handling


Selenium:-

  • Alert Handling by Clicking Accept Button
public class SeleniumJavaAlerts {
    public static WebDriver driver;
    public static void main(String[] args) throws InterruptedException {

        WebDriverManager.firefoxdriver().setup();
        driver = new FirefoxDriver();
        driver.get("https://the-internet.herokuapp.com/javascript_alerts");

        /**
         * Alert Handling by Clicking Accept Button
         */
        driver.findElement(By.xpath("//button[@onclick='jsAlert()']")).click();
        driver.switchTo().alert().accept();

        WebElement alertConfirmation = driver.findElement(By.xpath("//p[@id='result']"));
        Assert.assertEquals(alertConfirmation, "You successfully clicked an alert");
        driver.quit();
    }
}
  • Alert Handling by Clicking Close Button
public class SeleniumJavaAlerts {
    public static WebDriver driver;
    public static void main(String[] args) throws InterruptedException {

        WebDriverManager.firefoxdriver().setup();
        driver = new FirefoxDriver();
        driver.get("https://the-internet.herokuapp.com/javascript_alerts");

        /**
         * Alert handling by sending text and dismiss
         */

        driver.findElement(By.xpath("//button[@onclick='jsConfirm()']")).click();
        driver.switchTo().alert().dismiss();

        WebElement alertConfirmation = driver.findElement(By.xpath("//p[@id='result']"));
        Assert.assertEquals(alertConfirmation, "You clicked: Cancel");
        driver.quit();
    }
}
  • Alert Handling with Sending text and Click OK Button
public class SeleniumJavaAlerts {
    public static WebDriver driver;
    public static void main(String[] args) throws InterruptedException {
        WebDriverManager.firefoxdriver().setup();
        driver = new FirefoxDriver();
        driver.get("https://the-internet.herokuapp.com/javascript_alerts");

        /**
         * Alert handling by sending text and accepting
         */

        driver.findElement(By.xpath("//button[@onclick='jsPrompt()']")).click();
        Alert alertConfirm = driver.switchTo().alert();
        alertConfirm.sendKeys("Hi Vikum");
        alertConfirm.accept();

        WebElement alertConfirmation = driver.findElement(By.xpath("//p[@id='result']"));
        Assert.assertEquals(alertConfirmation, "Hi Vikum");

        driver.quit();
    }
}
  • Alert Handling with Sending text and Click Cancel Button
public class SeleniumJavaAlerts {
    public static WebDriver driver;
    public static void main(String[] args) throws InterruptedException {
        WebDriverManager.firefoxdriver().setup();
        driver = new FirefoxDriver();
        driver.get("https://the-internet.herokuapp.com/javascript_alerts");

        /**
         * Alert handling by sending text and accepting
         */

        driver.findElement(By.xpath("//button[@onclick='jsPrompt()']")).click();
        Alert alertConfirm = driver.switchTo().alert();
        alertConfirm.sendKeys("Hi Vikum");
        alertConfirm.dismiss();

        WebElement alertConfirmation = driver.findElement(By.xpath("//p[@id='result']"));
        Assert.assertEquals(alertConfirmation, "You entered: null");

        driver.quit();
    }
}


Cypress:-

  • Javascript Alert Window Handling

describe('Alert Handling', ()=>{

    it('01. Javascript Alert Window Handling', () =>{

        cy.visit("https://the-internet.herokuapp.com/javascript_alerts");

        cy.get("button[onclick='jsAlert()']").click();

        cy.on('window:alert', (alert) =>{

            expect(alert).to.contains('I am a JS Alert'); //Alert validation

            /**No need to write to close the alert window, it handles by Cypress */

        })

        cy.get("#result").should('have.text', 'You successfully clicked an alert');


    });

})

  • Javascript Confirm Alert Window Handling by Clicking OK Button

describe('Alert Handling', ()=>{

    it('02.  Javascript Confirm Alert - Clicking OK Button ', () =>{

        cy.visit("https://the-internet.herokuapp.com/javascript_alerts");

        cy.get("button[onclick='jsConfirm()']").click();

        cy.on('window:confirm', (alert) =>{

            expect(alert).to.contains('I am a JS Confirm');

            /**No need to write to close the alert window, it handles by Cypress */

        })

        cy.get("#result").should('have.text', 'You clicked: Ok');

    });

})

  • Javascript Confirm Alert Window Handling by Clicking Cancel Button

describe('Alert Handling', ()=>{

    it('03. Javascript Confirm Alert - Clicking Cancel Button', () =>{

cy.visit("https://the-internet.herokuapp.com/javascript_alerts");

        cy.get("button[onclick='jsConfirm()']").click();

        /**

         * By default cypress close the alert window by clicking OK button, If you need to close the window

         * by clicking Cancel button, you have to do as follow

         */

        cy.on('window:confirm', () => false);

        cy.get("#result").should('have.text', 'You clicked: Cancel');

    });

})

  • Javascript Prompt Alert Window Handling by Clicking OK Button

describe('Alert Handling', ()=>{

    it('04. Javascript Prompt Alert - Clicking OK Button', () =>{

cy.visit("https://the-internet.herokuapp.com/javascript_alerts");

        /**Here this kind of alert we need to pass some text to the alert */

        /**Before clicking the button need to get control of it. So trigger the following function*/

        cy.window().then((win) =>{

            cy.stub(win, 'prompt').returns('Welcome to Cypress');

        })

        cy.get("button[onclick='jsPrompt()']").click(); //then click the button

        /**Alert window automatically close by clicking the OK button from Cypress*/

        cy.get("#result").should('have.text', 'You entered: Welcome to Cypress');

    });

})

  • Javascript Prompt Alert Window Handling by Clicking Cancel Button

describe('Alert Handling', ()=>{

    it('05. Javascript Prompt Alert - Clicking Cancel Button', () =>{

        cy.visit("https://the-internet.herokuapp.com/javascript_alerts");

        /**Here this kind of alert we need to pass some text to the alert */

        /**Before clicking the button need to get control of it. So trigger the following function*/

        cy.window().then((win) =>{

            cy.stub(win, 'prompt').returns('Welcome to Cypress');

        })

        cy.get("button[onclick='jsPrompt()']").click(); //then click the button

        /**If you need to click the 'Cancel' button to close the alert window */

        cy.on('window:confirm', ()=> false)

        cy.get("#result").should('have.text', 'You entered: null');

    });

})

  • Authenticated Alert Handling - Approach 1

describe('Alert Handling', ()=>{

    it('06. Authenticated Alert Handling - Approach 1', () =>{

        /**Approach 01 -> Pass the username and password through the URL parameters */

        cy.visit("https://the-internet.herokuapp.com/basic_auth", {auth: {username: "admin", password: "admin"}});

        cy.get("div[class='example'] p").should('have.contain', 'Congratulations!');

    });

})


  •  Authenticated Alert Handling - Approach 2

describe('Alert Handling', ()=>{

    it('07. Authenticated Alert Handling - Approach 2', () =>{

        /**Approach 02 -> Directly inject the username and password to the URL */

        cy.visit("https://admin:admin@the-internet.herokuapp.com/basic_auth");


        cy.get("div[class='example'] p").should('have.contain', 'Congratulations!');

    });

})

Playwright:-

Dialogs or Alerts in Playwright

Dialogs or alerts are automatically dismissed by the playwright. It means the playwright automatically handles the alerts.

If you need to do some validation on the alerts or dialogs you can do as follows

Reference- https://playwright.dev/docs/dialogs

  • Alert handle by clicking the OK button
import {test, expect} from '@playwright/test'
test('Alert with ok button click', async({page}) =>{

    await page.goto("https://testautomationpractice.blogspot.com/");
     
    // 1. Enabling alert window handle
    page.on('dialog', async dialog =>{
        expect(dialog.type()).toContain('alert');
        expect(dialog.message()).toContain('I am alert box!!!');
        await dialog.accept();
    })

    // 2. Click the option you need to get the alert
    await page.click("//button[@onclick='myFunctionAlert()']");
    page.waitForTimeout(5000);
});
  • Confirm Alert Handle by clicking the OK button
import {test, expect} from '@playwright/test'
test('Alert with confirm button click - here having both OK and Cancel buttons - this is OK', async({page}) =>{

    await page.goto("https://testautomationpractice.blogspot.com/");
     
    // 1. Enabling alert window handle
    page.on('dialog', async dialog =>{
        expect(dialog.type()).toContain('confirm');
        expect(dialog.message()).toContain('Press a button!');
        await dialog.accept();
    })

    // 2. Click the option you need to get the alert
    await page.click("//button[@onclick='myFunctionConfirm()']");
    await expect(page.locator("//p[@id='demo']")).toHaveText("You pressed OK!");

    page.waitForTimeout(5000);
});
  • Confirm Alert Handle by clicking the Cancel button
import {test, expect} from '@playwright/test'
test('Alert with confirm button click - here having both OK and Cancel buttons - this is Cancle', async({page}) =>{

    await page.goto("https://testautomationpractice.blogspot.com/");
     
    // 1. Enabling alert window handle
    page.on('dialog', async dialog =>{
        expect(dialog.type()).toContain('confirm');
        expect(dialog.message()).toContain('Press a button!');
        await dialog.dismiss(); 
    })

    // 2. Click the option you need to get the alert
    await page.click("//button[@onclick='myFunctionConfirm()']");
    await expect(page.locator("//p[@id='demo']")).toHaveText("You pressed Cancel!");

    page.waitForTimeout(5000);
});
  • Prompt Alert Handle 
import {test, expect} from '@playwright/test'
test('Prompt dialog box - here sending text to the textbox', async({page}) =>{

    await page.goto("https://testautomationpractice.blogspot.com/");
     
    // 1. Enabling alert window handle
    page.on('dialog', async dialog =>{
        expect(dialog.type()).toContain('prompt');
        expect(dialog.message()).toContain('Please enter your name:');
        expect(dialog.defaultValue()).toContain("Harry Potter");
        await dialog.accept("Vikum"); 
    })

    // 2. Click the option you need to get the alert
    await page.click("//button[@onclick='myFunctionPrompt()']");
    await expect(page.locator("//p[@id='demo']")).toHaveText("Hello vikum! How are you today?");

    page.waitForTimeout(5000);
});


04. Assertions 


Selenium:-

There are two types of assertions

Hard Assertion

The test will stop once got the failed test.
        Eg:- Form validation, Navigation, Pop-ups, and alerts, Data validation, Performance testing
  • Assert.assertTrue()
  • Assert.assertFalse()
  • Assert.assertEquals()
@Test
void hardAssertions(){
  Assert.assertTrue(true); //pass
  Assert.assertEquals("welcome","welcome");
  Assert.assertFalse(false);
  System.out.println("Success...!!!");
}

Soft Assertion

If some test got a fail, the main suite will not stop until finishing the execution and it works through the object.
          Eg:- Checking multiple elements, Non-critical checks, Dynamic content, Conditional checks

SoftAssert softAssert = new SoftAssert();
  • softAssert.assertTrue(condition);
  • softAssert.assertFalse(condition);
  • softAssert.assertEquals(condition);
  • softAssert.assertAll(condition);
  • softAssert.onAssertFailure(condition);
@Test
void softAssert(){
   softAssert.assertTrue(true);
   softAssert.assertEquals("Welcome","Welcome");
   softAssert.assertEquals("Selenium","selenium");
   System.out.println("Good...!!!");
   softAssert.assertAll();
}

Cypress:-

Cypress has two types of Assertions. There are,

1). Implicit Assertions

2). Explicit Assertions


1). Implicit Assertions

Implicit Assertions is default and inbuild assertion in Cypress.

There are main two keywords. There are,

1). should

2). and

Reference - https://docs.cypress.io/guides/references/assertions

describe('Alert Handling', ()=>{

    it('Implicit Assertions', () =>{

        cy.visit("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");


        cy.url().should('include', 'orangehrmlive');

        cy.url().should('contain', 'orange')

        cy.url().should('eq', 'https://opensource-demo.orangehrmlive.com/web/index.php/auth/login');


        //If there is a multiple 'should' keyword repeating you can use it as follows

        cy.url().should('include', 'orangehrmlive')

        .and('include', 'orange')

        .and('not.include', 'viku');


        cy.title().should('include', 'Orange')

        .and('not.include', 'piku')

        .and('eq', 'OrangeHRM')

        .and('contain', 'HRM');


        cy.get("img[alt='company-branding']").should('be.visible')

        .and('exist');

        cy.get("//a").should('have.length', '5');

    });

})


2). Explicit Assertions

Explicit Assertions are the assertion that needs to be handled explicitly in Cypress.

There are main two keywords. There are,

1). expect(BDD)

2). assert(TDD)


Reference - https://docs.cypress.io/guides/references/assertions

describe('Alert Handling', ()=>{

    it.only('Explicit Assertions', () =>{

        cy.visit("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");

        cy.get("input[placeholder='Username']").type("admin");

        cy.get("input[placeholder='Password']").type("admin123");

        cy.get("button[type='submit']").click();

        cy.get(".oxd-topbar-header-title").then((x) =>{

            let PageHeader = x.text();

            expect(PageHeader).to.equal('Dashboard'); //BDD

            assert.equal(PageHeader, 'Dashboard'); //TDD

        });        

    })

})


Playwright:-

import {test, expect} from '@playwright/test'

test('Assertions', async({page}) =>{

    await page.goto("https://opensource-demo.orangehrmlive.com/");

    /**URL Validation */

    await expect(page).toHaveURL('https://opensource-demo.orangehrmlive.com/');

    /**Page Title validation */

    await expect(page).toHaveTitle('OrangeHRM');

    /**Element visibility validation */

    await expect(page.locator("img[alt='company-branding']")).toBeVisible();

    /**Element Inability validation */

    await expect(page.locator("button[type='submit']")).toBeEnabled();

})


05. Dropdown Handling


Selenium:-

  • Select tag Dropdown

public class SelectDropDown {

    public static void main(String args[]){

        WebDriverManager.chromedriver().setup();
        WebDriver driver = new ChromeDriver();

        driver.get("https://www.opencart.com");
        driver.manage().window().maximize();

        WebElement countryDrp = driver.findElement(By.xpath("(//select[@id='input-country'])[1]")); 

        Select options = new Select(countryDrp);
        List<WebElement> allOptions = options.getOptions();

        for (WebElement drp:allOptions){
            if (drp.getText().equals("Sri Lanka")){
                drp.click();
                break;
            }
        }
    }
}

  • Select tag Multi Dropdown Handling
public class SelectDropDown {

    public static void main(String args[]){

        WebDriverManager.chromedriver().setup();
        WebDriver driver = new ChromeDriver();

        driver.get("https://www.opencart.com");
        driver.manage().window().maximize();

WebElement abc = driver.findElement(By.xpath("asd"));
        commonDrpMethod(abc,"Sri Lanka"); 


        }
    }
    public static void commonDrpMethod(WebElement drp, String value){
    Select options = new Select(drp);
    List<WebElement> allOption = options.getOptions();

        for (WebElement AllOp:allOption){
            if (AllOp.getText().equals(value)){
                AllOp.click();
                break;
            }
        }
    }
}
  • Without Select tag or Bootstrap Dropdown
public class BoostrapDropDown {
    public static void main(String args[]) {
        WebDriverManager.chromedriver().setup();
        WebDriver driver = new ChromeDriver();

        driver.get("https://www.hdfcbank.com");
        driver.manage().window().maximize();
        /*
        * When bootstrap web, there you should click first to select the list down option
        *
        * */

        driver.findElement(By.xpath("//div[@class='drp']//div[@class='dropdown']")).click();

        //Capture the all option that is listed down
        List<WebElement> allOptions = driver.findElements(By.xpath("//ul[@class='dropdown-1']//li"));
        allOptions.size(); //find how many options

        for(WebElement options:allOptions){
            if (options.getText().equals("Account")){
                options.click();
                break;
            }
        }
    }
}
  • Auto Suggestion Dropdown
public class AutoSuggestionDropDown {
    public static void main(String[] args) {

        WebDriverManager.chromedriver().setup();
        WebDriver driver = new ChromeDriver();
        
        driver.get("https://www.bing.com");
        driver.manage().window().maximize();

        driver.findElement(By.xpath("//input[@id='sb_form_q']")).sendKeys("selenium");
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(3000));

        List<WebElement> list = driver.findElements(By.xpath("//li[@class='sa_sg']//span"));
        for (WebElement allOption:list){
            if (allOption.getText().equals("selenium webdriver")){ //here instead of equals u can use contains too
                allOption.click();
                break;
            }
        }
    }
}
  • Auto Complete Dropdown
public class AutoCompleteGooglePlaceholderDropdown {
    public static void main(String[] args) {

        WebDriverManager.chromedriver().setup();
        WebDriver driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(Duration.ofMillis(3000));

        driver.get("https://www.twoplugs.com");
        driver.manage().window().maximize();

        driver.findElement(By.xpath("//a[normalize-space()='Live Posting']")).click();

        WebElement searchbox = driver.findElement(By.id("autocomplete"));
        searchbox.click();

        searchbox.sendKeys("Toronto"); //when u enter this of the field u can't get the list down elements xpath

        //here we need to use the down or upper arrow key

        String text;

        do {
            searchbox.sendKeys(Keys.ARROW_DOWN);
            text = searchbox.getAttribute("value");

            if (text.equals("Toronto, OH, USA")){
                searchbox.sendKeys(Keys.ENTER);
                break;
            }
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }while (!text.isEmpty());
    }
}
  • Sorted Order Dropdown
You can do this as follows,
    - Get the listed dropdown options to the list
    - There should be two lists, one for the original and the other one for templist
    - Then sort the lists using 'Collection.sort()' 
    - Then check whether those lists are sorted in order or not with the equal() method.


Cypress:-

  • Select tag Dropdown Handling

describe('Dropdown Handling', ()=>{
it('Select tag dropdown', () =>{
        /**
         * 'Select' tag dropdown handling
         */
        cy.visit("https://www.zoho.com/commerce/free-demo.html");
        cy.get("#zcf_address_country").select('Sri Lanka').should('have.value', 'Sri Lanka');
    });
})

  • Without the 'Select' tag Dropdown Handling

describe('Dropdown Handling', ()=>{
it('Without Select tag dropdown', () =>{
        /**
         * Without the 'Select' tag dropdown handling
         */
        cy.visit("https://www.dummyticket.com/dummy-ticket-for-visa-application/");
        cy.get("#select2-billing_country-container").click();
        cy.get("input[role='combobox']").type("Sri Lanka").type('{enter}');
        cy.get("#select2-billing_country-container").should('have.text', 'Sri Lanka');
    });
})

  • Auto Suggestion Dropdown Handling

describe('Dropdown Handling', ()=>{
it('Auto suggested dropdown', () =>{
        cy.visit("https://wikipedia.org");
        cy.get("#searchInput").type('Automation');
        cy.get(".suggestion-title").contains('Automation Master').click();
        cy.get(".mw-page-title-main").should('have.text', 'Automation Master');
    });
})

  • Dynamic Dropdown Handling


describe('Dropdown Handling', ()=>{
it('Dynamic dropdown', () =>{
        cy.visit("https://www.google.com/");
        cy.get("#APjFqb").type('Cypress Automation');
        cy.wait(3000);
        cy.get("div.wM6W7d>span").should('have.length', 11);
        /**
         * Here we need to use the 'each' operation in Cypress
         * 
         * Reference - https://docs.cypress.io/api/commands/each
         */
        cy.get("div.wM6W7d>span").each(($ele, $index, $list) =>{
            if($ele.text() == "cypress automation tutorial"){
                cy.wrap($ele).click();
            }
        })
        cy.get("#APjFqb").should('have.value', 'cypress automation tutorial'); 
    });
})

Playwright:-

  • Select tag Dropdown Handling

import {test, expect} from '@playwright/test'
test('Select tag drop downs', async ({page}) =>{
    await page.goto("https://testautomationpractice.blogspot.com/");
    /**
     * There are multi ways of selecting an option from 'select' tag dropdowns
     */
    //There are multiple ways to select
    //await page.locator("#country").selectOption("Japan"); // using visible text
    //await page.locator("#country").selectOption({label:'Australia'}); // using label
    //await page.locator("#country").selectOption({value:'uk'}); // using value
    //await page.locator("#country").selectOption({index:3}); // using index
    await page.selectOption("#country", 'Australia');
    /**
     * Assertions: 
     */
    // 1. Count dropdown options: 
    const countries = await page.locator("#country option");
    await expect(countries).toHaveCount(10);
    // count dropdown option: Approach 2
    const lists = await page.$$("#country option");
    console.log("Country Count: ", lists.length);
    await expect(lists.length).toBe(10);
    // Check the required value from the dropdown - approach 1
    const countryList = await page.locator("#country").textContent();
    await expect(countryList.includes("Japan")).toBeTruthy();
    // Check the required value from the dropdown - approach 2(using for loop)
    const countryOptions = await page.$$("#country option");
    let status = false;
    for(const listOptions of countryOptions){
        if (listOptions.textContent().includes("India")){
            status=true;
            break;
        }
    }
    expect(status).toBeTruthy();
    /**
     * This is another way of selecting an option from the dropdown
     */
    const countryOptions2 = await page.$$("#country option");
    for(const listOptions2 of countryOptions2){
        let value = await listOptions2.textContent();
        if (value.includes("India")){
            
            await page.selectOption("#country", value);
            break;
        }
    }
    await page.waitForTimeout(5000);
})

  • Select Multi Choices from Select tag Dropdown

import {test, expect} from '@playwright/test'
test('Select multiple choices from select tag dropdowns', async ({page}) =>{
    await page.goto("https://testautomationpractice.blogspot.com/");
    await page.select option("#colors", ['Red', 'Blue', 'Green'])
    /**
     * Assertions: 
     */
    // 01. check the number of options in dropdowns
    const list = await page.locator("#color option");
    await expect(list).toHaveCount(5);

    // check the number of options using for loop
    const colorList = await page.$$("color option");
    const colorLen = colorList.length;
    await expect(colorLen).toBe(5)
    //check required text content out from the list
    await expect(colorList.textContent("Red")).toBeTruthy();
    await page.waitForTimeout(50000);
})

  • Bootstrap Dropdown Handling

import {test, expect} from '@playwright/test'
test('Boostrap dropdown automation', async({page})=>{
    await page.goto("https://www.jquery-az.com/boots/demo.php?ex=63.0_2");
    const choices = await page.locator("ul>li label input"); 
    await expect(choices).toHaveCount(11);
    //check the length
    const listChoice = page.$$("ul>li label input");
    await expect((await listChoice).length).toBe(11);
    // select multiple options
    for (const lists of listChoice){
       // console.log(lists.textContent());
       const value  = await lists.textContent();
        if(value.includes("Agular") && value.includes("Java")){
            await lists.click();
        }
    }
})

  • Auto Suggestion Dropdown Handling

import {test, expect} from '@playwright/test'
test('Auto Complete dropdown', async({page})=>{
    await page.goto("https://www.rebus.in/");
    await page.locator("#src").fill("Delhi");
    // Here after passing text to the text box you have to wait to get the list of suggestions. 
    // So use 'waitForSeletor' method
    await page.waitForSelector("//li[contains(@class,'sc-iwsKbI')]/div/text[1]");
    const list = await page.$$("//li[contains(@class,'sc-iwsKbI')]/div/text[1]");
    for(const lists of list){
        if(lists.textContent().includes("Anand Vihar")){
            await lists.click();
            break;
        }
    }
    await page.waitForTimeout(3000);
})

  • Hidden Items Capture from Dropdown

import {test, expect} from '@playwright/test'

test('Hidden Items capture from dropdown', async({page})=>{

    await page.goto("https://opensource-demo.orangehrmlive.com/");

    await page.locator("[name='username']").fill("admin");

    await page.locator("[name='password']").fill("admin123");

    await page.locator("[type='submit']").click();

    await page.locator("//span[normalize-space()='PIM']").click();

    await page.locator("//div[normalize-space()='-- Select --']")

    const list = await page.$$("//div[@role='listbox']//span");

    for(const lists of list){

        const joblist = await lists.textContent();

        if(joblist.includes("QA Engineer")){

            await lists.click;

            break;

        }

    }

    await waitForTimeout(5000);

})

06. iFrame Handling


Selenium:-

public class SeleniumIFrames {

    public static WebDriver driver;

    public static void main(String[] args) {

        WebDriverManager.firefoxdriver().setup();

        driver = new FirefoxDriver();

        driver.get("https://selenium.dev/selenium/docs/api/java/index.html?overview-summary.html");

        /**

         * If there is an iFrame, we can't access directly the link or any icon

         */

        driver.switchTo().frame("packageListFrame"); //name of the iframe

        driver.findElement(By.xpath("//a[normalize-space()='org.openqa.selenium']")).click();

        driver.switchTo().defaultContent(); //go out from the iframe or go to the main content of the page

    }

}

Cypress:-

import 'cypress-iframe'

describe('IFrame Handling', ()=>{

    it('IFrame Handling - Approach 01', () =>{

        cy.visit("http://the-internet.herokuapp.com/iframe");

        /**

         * Here first need to access the iframe. Then do what we want

         */

        //iframe -> [index]document ->

        const iframe = cy.get("#mce_0_ifr").its('0.contentDocument.body').should('be.visible').then(cy.wrap);

        iframe.clear().type("Welcome to Cypress {Ctrl+a}");

        /** if you want to select the typed text and click blot */

        //iframe.clear().type("Hii Welcome to Cypress {Ctrl+a}");

        //cy.get("[aria-label='Bold']").click();

    });

})


import 'cypress-iframe'

describe('IFrame Handling', ()=>{

it('IFrame Handling - Approach 02', () =>{

        cy.visit("http://the-internet.herokuapp.com/iframe");

        /**

         * Here write the command method for the iframe in the commands.js file in the support folder.

         * 

         * Cypress.Commands.add('getIframe',(iframe) => {

                return cy.get(iframe)

                .its('0.contentDocument.body')

                .should('be.visible')

                .then(cy.wrap);

            })

         */

        cy.getIframe('#mce_0_ifr').clear().type("Welcome to Cypress");

    });

})


import 'cypress-iframe'

describe('IFrame Handling', ()=>{

it('IFrame Handling - Approach 03 - Using iframe plugin', () =>{

        cy.visit("http://the-internet.herokuapp.com/iframe");

        /**

         * Install Cypress iframe plugin using the following command

         *      npm install -D cypress-iframe

         */

        cy.frameLoaded('#mce_0_ifr');

        cy.iframe('#mce_0_ifr').clear().type("Welcome to Cypress");

    });

})

Playwright:-

import {test, expect} from '@playwright/test'

test('IFrame', async({page}) =>{

    await page.goto("https://ui.vision/demo/webtest/frames/");


    // Get the all iframes on the page

    const iframes = await page.frames();

    console.log("Total IFrames: ",iframes.length);


    /**

     * Approach 01: using name or URL

     */

    const frame1 = await page.frame({url: "https://ui.vision/demo/webtest/frames/frame_1.html"});

    frame1.fill("[name='mytext1']", 'Hello Vikum');


    /**

     * Approach 02: using the locator

     */

    const inputbox = await page.frameLocator("frame[src='frame_1.html']").locator("[name='mytext1']");

    inputbox.fill("Hello pavi")

    await page.waitForTimeout(5000);

});


import {test, expect} from '@playwright/test'

test('Inner or Nested IFrames', async({page}) =>{

    await page.goto("https://ui.vision/demo/webtest/frames/");

    /**

     * Approach 01: using name or URL

     */

    const frame3 = await page.frame({url: "https://ui.vision/demo/webtest/frames/frame_3.html"});

    frame3.fill("[name='mytext3']", 'Hello Vikum');

    /**

     * Nested Frame Handle

     */

    const childFrames = await frame3.childFrames();

    await childFrames[0].locator("//div[@id='i5']//div[@class='AB7Lab Id5V1']").check();

    await page.waitForTimeout(5000);

});


07. Mouse Operations


Selenium:-

  • Mouse Hover Action

public class mouseHoverAction {
    public static void main(String[] args) {

        WebDriverManager.chromedriver().setup();
        WebDriver driver = new ChromeDriver();

        driver.get("https://demo.opencart.com");
        driver.manage().window().maximize();

        WebElement desktopMenu = driver.findElement(By.xpath("<locator>"));
        WebElement desktopChoice1 = driver.findElement(By.xpath("<locator>"));

        Actions actions = new Actions(driver);
        actions.moveToElement(desktopMenu).moveToElement(desktopChoice1).click().perform();
    }
}

  • Mouse RightClick Action

public class mouseRighClick {
    public static void main(String[] args) {

        WebDriverManager.chromedriver().setup();
        WebDriver driver = new ChromeDriver();

        driver.get("http://swisnl.github.io/jQuery-contextMenu/demo.html");
        driver.manage().window().maximize();

        WebElement button = driver.findElement(By.xpath("<locator>"));

        Actions actions = new Actions(driver); // need to pass the driver
        actions.contextClick(button).perform(); //Right click action(contextClick)
    }

  • Mouse DoubleClick Action
public class mouseDoubleClick {
    public static void main(String[] args) {

        WebDriverManager.chromedriver().setup();
        WebDriver driver = new ChromeDriver();

        driver.get("https://www.w3cschools.com/tags/tryit.asp?filename=tryhtml5_ev_ondblclick3");
        driver.manage().window().maximize();

        WebElement button = driver.findElement(By.xpath("//abc"));
        Actions actions = new Actions(driver);
        actions.doubleClick(button).perform();
    }
}
  • Mouse Drag and Drop Action

public class mouseDragAndDrop {

    public static void main(String[] args) {

        WebDriverManager.chromedriver().setup();

        WebDriver driver = new ChromeDriver();

        driver.get("https://www.dhtmlgoodies.com/scripts/drag-drop-custom/demo-drag-drop-3.html");

        driver.manage().window().maximize();

        /*

        * Here you should get the "Source Element" and the "Target Element"

        * */

        WebElement sourceEle = driver.findElement(By.xpath("//abc"));

        WebElement targetEle = driver.findElement(By.xpath("//abc"));

        Actions actions = new Actions(driver);

        actions.dragAndDrop(sourceEle,targetEle).perform();

    }

}

Cypress:-

  • Mouse Hover Action

describe('Mouse Operations', ()=>{
it('Mouse Hover Action', () =>{
        cy.visit("https://demo.opencart.com/");
        cy.get(".nav-link.dropdown-toggle]").trigger('mouseover').click();
        cy.get("body > main:nth-child(3)> a:nth-child(1)").click();
    });
})

  • Mouse Right Click Action

describe('Mouse Operations', ()=>{
it('RightClick Action - Approach 1', () =>{
        cy.visit("https://swisnl.github.io/jQuery-contextMenu/demo.html");
        cy.get(".context-menu-one.btn.btn-neutral").trigger('contextmenu');
        cy.get(".context-menu-icon-copy > span").should('be.visible');
    });
})

describe('Mouse Operations', ()=>{
it('RightClick Action - Approach 2', () =>{
        cy.visit("https://swisnl.github.io/jQuery-contextMenu/demo.html");
        cy.get(".context-menu-one.btn.btn-neutral").rightclick();
        cy.get(".context-menu-icon-copy > span").should('be.visible');
    });
})

  • Mouse Double Click Action

describe('Mouse Operations', ()=>{
it('DoubleClick Action - Approach 1 Trigger method using', () =>{
        cy.visit("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_ev_ondblclick");
        cy.frameLoaded("#iframeResult");

        cy.iframe('#iframeResult').find("button[ondbclick='myFunction()']").trigger('dblclick');
        cy.iframe('#iframeResult').find("#field2").should('have.text', 'Hello World');
    });
})

describe('Mouse Operations', ()=>{
it('DoubleClick Action - Approach 2 dblclick method', () =>{
        cy.visit("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_ev_ondblclick");
        cy.frameLoaded("#iframeResult");

        cy.iframe('#iframeResult').find("button[ondbclick='myFunction()']").dblclick();
        cy.iframe('#iframeResult').find("#field2").should('have.text', 'Hello World');
    });
})

  • Drag and Drop Action

import 'cypress-iframe'
require ('@4tw/cypress-drag-drop')

describe('Mouse Operations', ()=>{
it('Drag and Drop Action', () =>{
        /**
         * Install drag and drop plugin as follows,
         *      npm install --save-dev @4tw/cypress-drag-drop
         */

        cy.visit("http://dhtmlgoodies.com/scripts/drag-drop-custom/demo-drag-drop-3.html");
        cy.wait(3000);
        cy.get("#box6").drag("#box106", ({force:true})); //if some times element is hidden, you can add 'force'
    });
})

  • Scrolling Action


describe('Mouse Operations', ()=>{
it('Scrolling the page Action', () =>{
        cy.visit("https://www.countries-ofthe-world.com/flags-of-the-world.html");
        cy.get("img[alt='Flag of Sri Lanka']").scrollIntoView();
        cy.get("img[alt='   Flag of Sri Lanka']").should('be.visible');

        //then if you need to go to another element 
        cy.get("img[alt='Flag of Russia']").scrollIntoView({duration: 2000});
        cy.get("img[alt='Flag of Russia']").should('be.visible')
    });
})

Playwright:-

  • Mouse Hover Action

import {test, expect} from '@playwright/test'
test('Mouse Hover Action', async({page}) =>{
    await page.goto("https://demo.nopcommerce.com/");

    const DesktopMainMenue = await page.locator("(//a[normalize-space()='Computers'])[1]")
    const NotebookSubMenue = await page.locator("//ul[@class='top-menu notmobile']//a[normalize-space()='Notebooks']")

    await DesktopMainMenue.hover();
    await NotebookSubMenue.click();

    await page.waitForTimeout(5000)
});

  • Mouse RightClick Action
import {test, expect} from '@playwright/test'
test('Mouse RightClick Action', async({page}) =>{
    await page.goto("https://swisnl.github.io/jQuery-contextMenu/demo.html");

    const rightClickBtn = await page.locator("//span[@class='context-menu-one btn btn-neutral']");
    await rightClickBtn.click({rightClickBtn: 'right'});

    await page.waitForTimeout(5000)
});
  • Mouse DoubleClick Action
import {test, expect} from '@playwright/test'
test('Mouse DoubleClick Action', async({page}) =>{

    await page.goto("https://testautomationpractice.blogspot.com/");

    const copyFiled = await page.locator("(//button[normalize-space()='Copy Text'])[1]");
    const secondField = await page.locator("//input[@id='field2']");

    await copyFiled.dblclick();
    await expect(secondField).toHaveValue("Hello World!")
    await page.waitForTimeout(5000)
});
  • Mouse Drag and Drop Action
import {test, expect} from '@playwright/test'
test('Mouse Drag and Drop Action - Approach 01', async({page}) =>{

    await page.goto("https://testautomationpractice.blogspot.com/");

    const sourceEle = await page.locator("//div[@id='draggable']");
    const dropField = await page.locator("//div[@id='droppable']");

    await sourceEle.hover();
    await page.mouse.down();

    await dropField.hover();
    await page.mouse.up();

    await page.waitForTimeout(5000)
});


import {test, expect} from '@playwright/test'
test('Mouse Drag and Drop Action - Approach 02', async({page}) =>{

    await page.goto("https://testautomationpractice.blogspot.com/");

    const sourceEle = await page.locator("//div[@id='draggable']");
    const dropField = await page.locator("//div[@id='droppable']");

    await sourceEle.dragTo(dropField);

    await page.waitForTimeout(5000)
});

08. Capture Screenshot


Selenium:-

  • Take Full Page Screenshot

public class SeleniumScreeshots {
    public static WebDriver driver;

    public static void main(String[] args) throws IOException {
        WebDriverManager.firefoxdriver().setup();
        driver = new FirefoxDriver();
        driver.get("https://demo.nopcommerce.com");
        driver.manage().window().maximize();
        /**
         * Take Full Page screenshot 
         */
        TakesScreenshot takesScreenshot = (TakesScreenshot) driver;
        File PageScreenshot = takesScreenshot.getScreenshotAs(OutputType.FILE);
        File saveLocation = new File(".\\screenshots\\fullPageScreenshot.png");
        FileUtils.copyFile(PageScreenshot, saveLocation);
    }
}

  • Take a Section/Portion of the Page Screenshot

public class SeleniumScreeshots {
    public static WebDriver driver;
    public static void main(String[] args) throws IOException {
        WebDriverManager.firefoxdriver().setup();
        driver = new FirefoxDriver();

        driver.get("https://demo.nopcommerce.com");
        driver.manage().window().maximize();
        /**
         * Take a screenshot from the selection section
         */

        WebElement section = driver.findElement(By.xpath("//div[@class='product-grid home-page-product-grid']"));
        File src = section.getScreenshotAs(OutputType.FILE);
        File saveFile = new File(".\\screenshots\\sectionScreenshot.png");
        FileUtils.copyFile(src, saveFile);
    }
}

  • Take a Specific Element Screenshot

public class SeleniumScreeshots {
    public static WebDriver driver;
    public static void main(String[] args) throws IOException {
        WebDriverManager.firefoxdriver().setup();
        driver = new FirefoxDriver();

        driver.get("https://demo.nopcommerce.com");
        driver.manage().window().maximize();
        /**
         * Take a screenshot from the element
         */

        WebElement section = driver.findElement(By.xpath("//div[@class='com']"));
        File src = section.getScreenshotAs(OutputType.FILE);
        File saveFile = new File(".\\screenshots\\sectionScreenshot.png");
        FileUtils.copyFile(src, saveFile);
    }
}


Cypress:-


Playwright:-

  • Page screenshot

import {test, expect} from '@playwright/test'

test('Page screenshot', async({page}) =>{

    await page.goto("https://demo.nopcommerce.com/computers");

    await page.screenshot({path: 'tests/screenshots/'+Date.now()+'HomePage.png'}); //here getting the Date method

    //because of, the same SS same from the same name. so I need to save it through the timestamp.

});

  • Full Page screenshot
import {test, expect} from '@playwright/test'
test('Full Page screenshot', async({page}) =>{
    await page.goto("https://demo.nopcommerce.com/computers");
    await page.screenshot({path: 'tests/screenshots/'+Date.now()+'FullPage.png', fullPage: true}); 
});
  • Element screenshot
import {test, expect} from '@playwright/test'
test('Element screenshot', async({page}) =>{
    await page.goto("https://demo.nopcommerce.com/computers");
    await page.locator("//div[@class='item-grid']").screenshot({path: 'tests/screenshots/'+Date.now()+'Computers.png'}); 
});
  • Playwright locators
To get the screenshot at the end of each test case, Please check the 'playwright.config' file's 'use' tag.
There is a 'screenshot: 'on' tag.

Execute the following code and check 'playwright-report' folder 'index.html report, there will be a screenshot attached to the HTML report.

npx playwright test tests/TakeScreenshots.spec.js --project chromium --headed show-report

import {test, expect} from '@playwright/test'
test.only('Playwright locators', async({page})=>{
    await page.goto("https://www.demoblaze.com/index.html");
    await page.getByRole('link', { name: 'Log in'}).click();
    await page.locator('#loginusername').fill('vikum') ;
    await page.locator('#loginpassword').fill('1qaz2wsx@');
    await page.getByRole('button', { name: 'Log in'}).click();
})

Unlock Web Testing Excellence: Comprehensive Cypress Cheat Sheet !

  Unlock the Full Potential of Cypress with Our Comprehensive Cheat Sheet! Welcome to my blog!   If you're a QA engineer or a test autom...

Most popular