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

Tips for determining if an array of objects, into which I am adding objects, contains a particular key value present in a different array of objects

I've been working on this and here is what I have tried so far: groceryList = []; ngOnInit() { this._recipesSub = this.recipesService.recipes.subscribe((receivedData) => { this.loadedRecipes = receivedData.recipes; }); } onCheckRecipe(e) { ...

having trouble parsing JSON data

Recently, I decided to experiment with JSON and utilized json_encode to generate a JSON object structured as shown below: [{ "timestamp": "12\/16\/2013 0:00", "curr_property": "7211", "curr_property_cost": "123", "day_pro ...

The call stack limit has been exceeded in VueJS/VueX

I'm currently developing a Vue project with Vuex for state management. However, I encountered a Maximum call stack size exceeded error in my console when attempting to bind actions and getters in my component using mapActions and mapGetters. I'm ...

Can integer values be stored in localStorage similar to JavaScript objects and retrieved without requiring typecasting?

After setting an integer value to a localStorage item: localStorage.setItem('a', 1) and checking its data type: typeof(localStorage.a) "string" it shows as a string. I then typecast it to an int for my purposes: parseInt(localStorage.a) My ...

Prevent Chrome extension from triggering HTTP authentication popup (digest)

Currently in the process of developing a chrome extension that requires access to http-auth protected resources (webdav), particularly those using digest authentication. I have successfully implemented authentication directly within the ajax request by ut ...

The installation of robotjs via npm failed due to issues encountered while trying to build the binaries

After attempting to execute the command "npm install robotjs -g," an error is thrown back at me. [email protected] install C:\Users\Ehsan\AppData\Roaming\npm\node_modules\robotjs prebuild-install || node-gyp reb ...

How to set DIVS to be hidden when the page first loads

I am currently working on a project where I need to use JavaScript to hide certain <div> elements when the page loads. I have also included jQuery in my code. Below is what I have tried so far: $(document).ready(function() { hide(); function hid ...

Customizing Material UI Select for background and focus colors

I am looking to customize the appearance of the select component by changing the background color to "grey", as well as adjusting the label and border colors from blue to a different color when clicking on the select box. Can anyone assist me with this? B ...

What is preventing Bootstrap properties from being applied to HTML elements appended to the DOM through JavaScript?

Currently, I am immersed in a project that utilizes Bootstrap to generate various nested components styled in accordance with Bootstrap's class system. I triumphantly crafted a card component using Bootstrap, but encountered a challenge when attemptin ...

Determine the percentage of clicks on an HTML5 canvas radial progress bar

Recently, I designed a circular progress bar displaying a specific percentage. However, I am facing a challenge in determining how to calculate the percentage when a user clicks on either the black or green part of the circle. Could you provide insight on ...

Auto-scrolling text box cursor movement

My query is quite similar to the topic discussed in this thread on automatic newline in textarea. However, my situation involves multiple textareas with a 1-row attribute, making it seem like writing on air due to the absence of visible borders (I've ...

Transform array sequences into their own unique sequences

Reorder Array of List to Fit My Custom Order Current Output: [ { "key": "DG Power Output", "value": "6.00", "unit": "kWh", }, { "key": "DG Run Time", "value": "5999999952", "unit": "minutes", }, { "key": "Fuel Level (Before)", "value": "8.00" ...

Update the state when a button is clicked and send a request using Axios

Currently in my front end (using react): import '../styles/TourPage.css'; import React, { Component } from 'react'; import axios from 'axios' class TourPage extends Component { constructor(props) { super(p ...

How can I use Selenium to verify if the data I input into the search button is being displayed on the webpage?

While attempting to choose a value from a dropdown using a selenium script, an error was encountered in the console stating: "Exception in thread "main" enter code here org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have b ...

Can you please explain the process of retrieving the value of an item from a drop-down menu using JavaScript?

I am currently developing a basic tax calculator that requires retrieving the value of an element from a drop-down menu (specifically, the chosen state) and then adding the income tax rate for that state to a variable for future calculations. Below is the ...

"Enhance Your Smart Contract Interaction with Algrand's Method Calling

Currently, I am working on integrating an Algorand smart contract with a Next.js application. To sign transactions, I am utilizing Pera wallet. However, I have encountered an issue when attempting to call methods from the contract on the front end using th ...

Issue with Ng-style not functioning properly when setting background color

I am struggling to set the background of an element using a configuration object with ng-style. For some unknown reason, I can't seem to make it work and I'm finding it really perplexing. The element I'm attempting to configure: <div id ...

What is the method for establishing session or cookie in an HTTPS request to a specific URL?

When making an HTTPS GET request in Node.js to a specific URL, it is necessary to include the session cookie. In this case, I already have the value of the cookie that needs to be sent. var URL = require('url-parse'); var appurl = "https://test ...

Angular 12 app does not have Express server searching for static files

Context I am in the process of transferring an Angular application to a GKE cluster. Unfortunately, due to company policy, the base docker image I am required to use does not support the installation of new software such as shell or Angular CLI commands l ...

Fetching Data from Response Headers in Angular 4.3.3 HttpClient

(Text Editor: Visual Studio Code; TypeScript Version: 2.2.1) The main objective here is to fetch the headers of the response from a request Let's consider a scenario where we make a POST request using HttpClient within a service: import { Injec ...