I am currently attempting to find a color picker element within a parent class using Cypress CSS Locator. While I am able to reach the parent element, I am unsure of the correct method to target the

My user interface has a list of elements displayed in 2 columns. The first column shows the name of the item, such as Manager, Operator, and the list is expected to grow. The second column consists of a color picker element where you can choose a color. I am currently trying to locate the color picker element for a specific name, for example, for Operator. I need to iterate over the elements and find the color picker element for Operator. Below is an HTML code snippet I would like to locate:

<span tabindex="0" class="colour-select" style="color: rgb(0, 0, 0); background-color: rgb(255, 255, 255);"></span>

To retrieve the list of name elements, I am using the following CSS selector:

li[class='cdk-drag item container-fluid'] span[class='form-control'] 

However, I am uncertain about how to proceed further to access the colour-select class in the code snippet above.

When examining the HTML code snippet provided:

<li _ngcontent-ppo-c336="" cdkdrag="" class="cdk-drag item container-fluid" ng-reflect-ng-class="[object Object]" ng-reflect-data="[object Object]" ng-reflect-disabled="false" rowid="370" orderid="0">
   <div _ngcontent-ppo-c336="" class="row">
      ...
   </div>
</li>

I am seeking guidance on which CSS locator to utilize in order to access the colour-select class. Any assistance provided would be greatly appreciated.

Thank you for your help.

- Riaz

Answer №1

When utilizing the .within() method, make sure to navigate upwards using the parents command


const AudienceResourceText = ["Undefined", "Manager", "Operator", "Minor"];

cy.get("li[class='cdk-drag item container-fluid'] span[class='form-control']")
.each((item, index, list) => {
  cy.wrap(item)
    .should("contain.text", AudienceResourceText[index])   // subject is span
    .parents('.row')                                       // subject is div.row
    .within(() => {                         
      cy.get('span.colour-select')                         // gets the color-picker
        .should('have.css', 'color', 'rgb(0, 0, 0)')       // check the color
    })
})

Answer №2

The issue lies with the specificity of the .get() selector.

Consider the following simplified HTML structure:

<li>
  <div class="row">
    <div class="col...">
      <span>TEXT-TO-FIND</span>
    </div>
    <div class="col...">
      <arm-colour-picker...
    </div>
  </div>
</li>

If you modify the selector to

li[class='cdk-drag item container-fluid'] .row
, you will target the rows containing both the text and the color-picker.

The

.should("contain.text", ...)
function searches through all children of the specified element, maintaining the expected behavior.

cy.get("li[class='cdk-drag item container-fluid'] .row")
  .each((item, index) => {
    cy.wrap(item)
      .should("contain.text", AudienceResourceText[index])
      .find('span.colour-select')
  })
}

This addresses the query regarding selecting the color-picker, though there are additional challenges related to method return.

Perhaps you intend to implement the following:

static get AudienceColour(): Cypress.Chainable<JQuery<HTMLElement>> {                

  const colors = []
  return cy.get("li[class='cdk-drag item container-fluid'] .row")
    .each((item, index) => {
      cy.wrap(item)
        .should("contain.text", AudienceResourceText[index])
        .find('span.colour-select')
        .invoke('attr', 'style')     // retrieve style attributes
        .then(styles => colors.push(styles)
    })
    .then(() => return colors)
}


Answer №3

To achieve this, utilize the within() function

cy.get(
  "li[class='cdk-drag item container-fluid'] span[class='form-control']"
).each((item, index, list) => {
  cy.wrap(item).within(() => {
    expect(item).to.have.text(AudienceResourceText[index])
    cy.get('.colour-select') //obtains the color-select class
  })
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing a click event listener on an iframe that has been dynamically generated within another iframe

Below is the code I used to attach a click event to an iframe: $("#myframe").load(function() { $(this.contentWindow.document).on('click', function() { alert("It's working properly"); }); }) Everything seems to be working co ...

What is the best way to retain previous values without using an object array to store values in a React state?

My approach involves storing the previous values in an array of objects, where each object represents a key-value pair. For example: [{ActFollow: 'BlN'},{ActSendGift: 'BlY'},{ActSubscribe: 'BlY'}]. However, I aim to transform ...

Storing Firestore Timestamp as a Map in the database

Snippet Below const start = new Date(this.date + 'T' + this.time); console.log(start); // Thu Sep 12 2019 04:00:00 GMT+0200 const tournament:Tournament = { start: firebase.firestore.Timestamp.fromDate(start) } When passing the tournament ...

I'm having trouble getting the code to work properly after the "else" statement using both jQuery and Javascript. My head is

Being a newcomer to javascript and jquery, debugging and viewing log files seem like a challenge compared to php. Any help from experienced individuals would be greatly appreciated. Although my code mostly works fine, I'm having trouble with the if/e ...

I'm looking to fill multiple input boxes with the same value

I am looking to pass the same value to multiple input boxes. Currently, the script below only displays in one box but I want to display the main box result in all multiple input boxes. <script type='text/javascript' src='http://code.jque ...

Injecting JavaScript object values into dynamically generated modal

I have a JavaScript object that contains various training courses. Each category includes multiple training courses, and each course is associated with a specific category. Currently, I am able to display the title and description of each category in a mo ...

Generating a hyperlink to a specific user ID within a data table

I'm facing an issue with the formatting of my simple table when trying to navigate to user.id. Is there a better approach to this or should I consider moving LinkToUser? All styling has been removed to avoid any conflicts. import styled from 'st ...

Encountering an Invalid Cookie Domain Exception with Selenium WebDriver when increasing thread count to 20, yet functions properly with 15 threads

Within my Selenium automation framework, I have been able to successfully run scripts in parallel with a thread count of 15. However, when attempting to increase the thread count to 20 or 30, an issue arises. org.openqa.selenium.InvalidCookieDomainExceptio ...

Searching dynamically using class names with JQuery

I am seeking to create a dynamic search input based on the class names within the span tags. However, I am struggling with displaying the class name that I have identified. My goal is to show the class names that match the entered value in the input on the ...

Enhancing Dataset Quality: Incorporating Failed Results with Apify

We have implemented the Apify Web Scraper actor to execute a URL validation task that retrieves the input URL, the title of the page, and the HTTP response status code. Our testing includes 5 URLs - 4 valid ones and 1 non-existent URL. The successful resul ...

I am having trouble getting my getColor() method to correctly change colors based on the data provided

When using a datatable, there are two columns: status and priority. The STATUS LIST includes OPEN or CLOSED, while the PRIORITY LIST includes HIGH, MODERATE, and LOW. So, if the status is open, it should be displayed in red color; if closed, then in green. ...

Parsing JSON or eliminating double quotation marks in data acquired from a model or database within the Rails framework

foo.html.erb <script type="text/javascript"> var all_user_data = <%= @user.all_user_bar_chart.to_json.html_safe) %>; </script> abc.js $(function () { if ($("#foo").length > 0){ var user_charts = new Highcharts.Chart({ ...

Encountering a script error that reads "TypeError: $ is not defined as a function

I am attempting to send an email using web services in asp.net, utilizing html and sending the information through a jquery ajax function. Below is the html form: <div class="col-md-6"> <h2>DROP ME A LINE</h2> & ...

What is the best way to combine the existing array data with the previous array data in JavaScript?

I am implementing server-side pagination in my MERN project. Let's say I retrieve 100 products from the database and want to display only 30 products, with 10 products per page. When a user navigates to the 4th page, I need to make another API call to ...

Methods for presenting text from an object array using Angular

I'm running into a bit of trouble with getting my text to show up properly in my code. In the HTML, I have <td>{{cabinetDetails.cabinetType}}</td> and my data source is set as $scope.cabinetDetails = [{cabinetType: 'panel'}]; De ...

Use $parse to extract the field names that include the dot character

Suppose I have an object with a field that contains a dot character, and I want to parse it using $parse. For instance, the following code currently logs undefined - var getter = $parse('IhaveDot.here'); var context = {"IhaveDot.here": 'Th ...

React drag and drop feature now comes with autoscroll functionality, making

I am encountering an issue with my nested list Items that are draggable and droppable. When I reach the bottom of the page, I want it to automatically scroll down. Take a look at the screenshot below: https://i.sstatic.net/ADI2f.png As shown in the image ...

Error: Angular encountered an undefined variable when attempting to import 'node_modules/bootstrap/scss/grid'

Having some trouble setting up Angular with SCSS and Bootstrap. When attempting to run ng serve, I encountered the following error: ./src/styles.scss - Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js): SassError: Undefined variable. ...

What is the process by which JavaScript evaluates the closing parenthesis?

I'm currently working on a calculator project that involves evaluating expressions like (5+4). The approach I am taking is to pass the pressed buttons into an array and then create a parse tree based on the data in that array. One issue I'm faci ...

ng-include not functioning properly within ng-table

In the table, there is a data structure <tr ng-repeat="question in $data" ng-include="'/views/partials/questionList.html'"></tr> Within the questionList.html file: <td class="top-td" data-title="'ID'" sortable="&ap ...