Skip to main content

Cypress Select from Drop Down List

Static dropdown have <select> tag while dynamic dropdown can have <nb-select>, <ng-select> or any other tag. Static dropdown with select tag can be easily handled using Cypress select command.

Dynamic dropdown could be auto suggestive or it can be a list as well. In this example we will handle Dynamic Dropdown List for ngx-admin application. Below is the screenshot for the dropdown in ngx-admin application

Dynamic dropdown in Cypress

ngx-admin application

Here you can see we have different values for dropdown Light, Dark, Cosmic and Corporate. When you will select any of the value the theme of header will be change accordingly. Below is the code to handle above dropdown, for demo watch the video embedded below:

How to Handle Dropdown in Cypress

  it.only('verify dropdown', () =>{
    // Visit the homepage
    cy.visit("/");
   
   // Get the drodown
    cy.get("nav nb-select").then(dropdown =>{
      // Click on drodown
      cy.wrap(dropdown).click()
      
      // Iterate through each option, Here, index default value is 0
      cy.get("ul.option-list nb-option").each((listItem,index) =>{
        
        // ItemText to store Options value like Light, Dark, etc.
        const colorName = listItem.text().trim()
        
        //colorList will store color name and RGB value of each color in json format
        const colorsList = {
          "Light":"rgb(255, 255, 255)",
          "Dark":"rgb(34, 43, 69)",
          "Cosmic":"rgb(50, 50, 89)",
          "Corporate":"rgb(255, 255, 255)"
        }
         
        // Click on each list item
        cy.wrap(listItem).click()
        
        // Verify dropdown value after selection 
        cy.wrap(dropdown).should('contain',colorName)
        
        // Verify color value after selection
        cy.get("nb-layout-header").should("have.css","background-color",colorsList[colorName]);
        
        // Do not open dropdown for last selection
        if(index < 3)
        {
          cy.wrap(dropdown).click()
        } 

      })
    })
  })

In above example, we have used

const: Constants are block-scoped, much like variables declared using the let keyword. The value of a constant can't be changed through reassignment, and it can't be redeclared. 

Tags
Submitted by tgoswami on August 17, 2021

Tarun has 11+ years of experience in Quality Assurance in different domains like Banking, E-commerce, Health and Education.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.