Cypress Select from Dynamic Drop Down

Profile picture for user devraj

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.