Ensuring that a group of items adhere to a specific guideline using JavaScript promises

I need to search through a series of titles that follow the format:

<div class='items'>
  * Some | Text *
</div>

or

<div class='items'>
  * Some more | Text *
</div>

There are multiple blocks on the page with these patterns, and I want to loop through them all to ensure they contain '* Some [more] | Text *', where [more] is optional and * can be any text.

My current code snippet looks like this:

yield browser

...Some code...

.elements('.items')
 .then((elementList)=>{
  for(var i = 0; i < elementList.value.length; i++){

   this.elementIdText(elementList.value[i].ELEMENT)
    .then((currElement)=>{
      var str = currElement.value;
      if(str.indexOf("Some | Text") == -1 || str.indexOf("Some more | Text") == -1){
       assert.ok(false, 'invalid string');
      }
    })

  }
 })

However, it appears that the asserts are being ignored because they're inside a for loop, which may cause synchronization issues.

Although I want the program to fail as soon as one of the strings does not match the required pattern, so I thought using a loop was necessary.

Is there a better way to achieve this?

The current behavior shows a console.log inside the for loop:

Command: find element
Command: find element
... n times
log: element 1 text
log: element 2 text
... n times

Instead of the preferred:

Command
log
Command
log
... n times 

Answer №1

Discovered a resolution without relying on the q promise library!

(Another option would have been to utilize the .all([]).then() function provided by q)

yield browser

...Some code...

.elements('.items')
 .then((elementList)=>{

  var chain = this; // initiating a promise chain

  for(var i = 0; i < elementList.value.length; i++){

   // incorporating each promise in the chain during every iteration
   chain = chain.elementIdText(elementList.value[i].ELEMENT)
            .then((currElement)=>{
              var str = currElement.value;
              if(str.indexOf("Some | Text") == -1 || str.indexOf("Some more | Text") == -1){
               assert.ok(false, 'invalid string');
              }
            })

  }

  // Returning the chain of promises created
  return chain;
 })

The concept behind using .then is that it signifies a promise where the content inside will eventually be processed. This implies that the content may not be executed until after the test has ended.

In contrast to potentially adding pauses (maybe?), forming a series of promises ensures that the subsequent promise isn't executed until the prior one, resulting in the completion of the test after all the code has been executed.

Answer №2

If you follow the steps below, it may help you significantly:

    //assuming I am loading a list of elements using the driver
    List<String> data=new ArrayList<>();

    data.add("murali");

    data.add("murali [selenium]");

    //loop through the list to iterate
    for(int i=0; i<data.size(); i++){

        //use assertion to verify the data retrieved from the list with the expected values
        //you can customize this based on your requirements
        //if any element in the list fails, the assert statement will stop checking further elements
        assert data.get(i)=="murali" || data.get(i)=="murali [selenium]";
    }

It is advisable to modify the assert command above according to your specific case rather than simply using 'equals'.

Thank You, Murali

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

Creating Vue components and including Javascript code within them

Attempting to develop a component using Vue for my JavaScript code, but encountering issues. My primary aim is to build a component with either Vue or Vue3 <head> <title></title> <script src="https://cdn.jsdelivr ...

Conceal specific pages within the DataTable without deleting them

Currently, I am facing an issue where the dataTable paginates and removes the DOM pages along with the data. My goal is to extract all the data from the dataTable and convert it to JSON without losing access to the DOM when pagination occurs. I want to m ...

Utilize a Python script to transmit data to JavaScript through JSON in order to dynamically alter the content of

Currently, I am developing an interactive display that utilizes sensors on a raspberry pi. The display is set to show a webpage and I have implemented a python script to handle sensor interaction. My goal is to change the displayed web page when a user p ...

Ways to verify the functionality of a webpage once it has been loaded on my local machine's browser

I manage a website that is currently hosted on a server and being used by thousands of visitors. The site is created using Java and soy template technology. I am looking to test the frontend rendering and JavaScript files. Can this be done directly from my ...

Leveraging the power of Google Closure Templates alongside the versatility of

We are embarking on developing an application using JavaScript and HTML5 that will utilize a rest API to access server resources, leveraging the power and convenience of jQuery which our development team is already proficient in. Our goal is to make this a ...

Setting a bookmark feature in HTML using localStorage: A step-by-step guide

I'm working on a simple code that captures the text content of a dynamically updated <h1> element and stores it as a "bookmark" in localStorage. I want to enable users to save or delete the bookmark by clicking a button. Below is a basic version ...

Filtering an array dynamically by utilizing an array of conditions

Can jQuery-QueryBuilder be used to filter an array? This amazing plugin generates a unique array of conditions: condition:"AND" rules: { field:"name" id:"name" input:"select" operator:"equal" type:"string" value:"Albert" } I have ...

Having trouble getting a response when using formidable in Next.js?

I am working on uploading a file from the front end to my GCP workflow, and everything seems to be functioning correctly. However, I am consistently encountering an issue where the API resolved without sending a response message appears. I attempted to r ...

jqgrid's date restriction is set to November 30th, 1999 at midnight

I have a table displaying DATETIME values. However, after editing the datetime value, it always changes to "1999-11-30 00:00:00", both in jqgrid and the database, regardless of the date entered. [Tue Mar 12 11:39:28 2013] [error] [client 171.43.1.4] PHP N ...

Transform the selected component in Material-UI from being a function to a class

Hello, I am currently learning about React and I have started using the select button from material-ui. The code I found on the material ui page is for a functional component, but I am more comfortable with class components. Here is the code snippet provid ...

Tips for deleting multiple objects from an array in angular version 13

I am facing an issue where I am trying to delete multiple objects from an array by selecting the checkbox on a table row. However, I am only able to delete one item at a time. How can I resolve this problem and successfully delete multiple selected objects ...

Challenges with sending JSON encoded Arrays from WordPress to PHP results in empty or NULL responses

My Plugins site has multiple Inputs that I need to gather values from and push them into an array. Then, I utilize the jQuery.post method to send this data to my PHP script. Javascript: var json = JSON.stringify(output); // output is an array with multip ...

Display a division in C# MVC 4 when a boolean value is true by using @Html.DropDownList

I have multiple divs stacked on top of each other, and I want another div to appear when a certain value is selected. I'm familiar with using JavaScript for this task, but how can I achieve it using Razor? Below is a snippet of my code: <div id=" ...

Encountering a java.lang.NullPointerException while utilizing Selenium WebDriver

I keep encountering a java.lang.NullPointerException when executing the test case in Eclipse. Any assistance in identifying the error I might have made would be greatly appreciated. Error @ Line 17: Issue with WebElement in LoginPage.Java. @ Line 12: Logi ...

Working with a Mix of Properties in Styled Components

Incorporating a button component with material design using styled-components is my current task. This component will possess various props including size, icon, floating, etc. However, managing the numerous combinations of props has become quite overwhel ...

Switching Perspective on Live ExpressJS Path -- Node.JS

I previously set up an express route with a template. Here's the code: app.get('/route', function route(req, res) { db.get('db_ID', function compileAndRender(err, doc) { var stream = mu.compileAndRender('theme-file.e ...

Using JavaScript to detect the Facebook like button on a webpage

I am currently developing an application for Facebook using HTML and Javascript. My goal is to be able to detect when a user clicks the "Like" button on my company's Facebook page without needing to embed a separate "Like" button within my app itself. ...

Oops! Looks like the connection has been abruptly cut off from the ASYNC node

Is there a way to properly close an async connection once all data has been successfully entered? Despite attempting to end the connection outside of the loop, it seems that the structure is being finalized after the first INSERT operation CODE require( ...

Retrieve the source code of a webpage by accessing its URL with JavaScript through the use of JSONP

To extract the source code from a URL web page using JSONP, you can use the following code snippet: <script type="text/javascript"> var your_url = ''; $(document).ready(function(){ jQuery.ajax = (function(_ajax){ var protocol = location. ...

Python, Selenium: Extract Specific Element from List of Results

By leveraging various resources such as reading materials, videos, Stack Overflow, and community support, I successfully extracted data from Tessco.com using a combination of Selenium and Python. Authentication credentials are required for this website. H ...