What is the best way to access a nested promise element in Protractor?

I've recently put together a function in protractor that I'd like to share:

function findChildElementByText(parentElement, tagName, textToSearch)
{
    return parentElement.all(by.tagName(tagName))
    .then((items) => {
      items.map( item => {
        item.getText().then(text => {
          if (text === textToSearch){
            return item;
          }
        });
      });
    });
}

Here's an example of how you can use this function to locate <option> elements within a <select> element:

let myitem = selectorHelpers.findChildElementByText(clientIdSelect, 'option', 'ExampleText');
myitem.click();

However, when I try to click on the element, I encounter the following error message:

Failed: myitem.click is not a function

Can someone help me modify this function so that it returns the correct item based on the text criteria and enables me to click on the element as illustrated in the example above?

Answer №1

It may not always be ideal to use the map method for retrieving a single element. This is because map creates a new array based on the returned value of each item.

Instead, you could consider utilizing a for...of loop or a traditional for loop to iterate over each item. Incorporating async / await will allow the program to wait for each item.getText() operation to resolve before moving on to the next item. If the awaited result matches the textToSearch, the function can return the item object. Otherwise, null can be returned after completing the loop.

function getChildElementByText(parentElement, tagName, textToSearch) {
  return parentElement.all(by.tagName(tagName))
    .then(async items => {
      for (const item of items) {
        const text = await item.getText();
        if (text === textToSearch) {
          return item;
        }
      }
      return null;
    });
}

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

Google Chrome repeatedly crashes when running several instances of Chrome Driver

I've been working on an app that utilizes multiple chrome driver instances by implementing a multiThreaded approach. Essentially, I create individual threads that each open numerous chrome drivers to retrieve information from specific URLs. As I scale ...

The execution of babel-node falters while the babel cli functions flawlessly

UPDATE: The issue was resolved by removing type=module from package.json I'm attempting to utilize babel-node, but it's not recognizing presets from .babelrc. Strangely, the babel CLI is functioning properly. This command works as expected: $ n ...

Is it possible to access the chrome://webrtc-internals/ variables through an API in JavaScript?

I couldn't find any information about how to access the logged variables in chrome://webrtc-internals/ on google. There is not even a description of the graphs available there. I am specifically interested in packetsLost, googCurrentDelayMs, and goo ...

Sort through the API's array

Currently, I am working with the OpenWeather API's 5-day 3-hour forecast feature and encountering an issue regarding the response JSON. The array contains 40 items, each with a "dt_txt" value in the format of "2018-11-22 15:00:00". My goal is to displ ...

Explore how Next.js's getServerSideProps feature incorporates loading animations and improves

I have implemented getServerSideProps in my project's pages/post/index.js file: import React from "react"; import Layout from "../../components/Layout"; function Post({ post }) { console.log("in render", post); return ( <Layout title={pos ...

Switching between different elements in an array using React

I've got a collection of appointments and I need to create a React view that will show them one by one. Users should be able to navigate through the appointments using arrow buttons. Here's an example of what the data looks like: const arr = [ ...

Struggling to retrieve the accurate input value when the browser's return button is clicked?

Having multiple forms created for different conditions, each one submits to a different page. However, when I navigate back from the other page, all my forms display the same values as before. Here's the code snippet: <form action="<?php echo b ...

Error encountered: Selenium unable to locate element exception when attempting to log in to OneDrive website (attempted various methods of locating elements

I have a plan to create a script that will automate the login process on the OneDrive website using Selenium. Both Google Chrome and Chromedriver Version are at 74. But I keep encountering the NoSuchElementException and I'm not sure why. I haven' ...

Utilizing Vue refs to set focus on a specific element target

Clicking on "span class="before-click" should hide it, and display input class="after-click" instead. The displayed input must be in focus! However, when trying to use $refs.afterClick to access the DOM and apply .focus(), an unexpected error stati ...

How can the Angular Js framework be utilized to create a pop-up feature in combination with Bootstrap?

I'm currently working on a website using AngularJS and Bootstrap. When the site is loading, I make a server call to fetch some data. This process takes some time, and during this interval, I want to display a pop-up message indicating that the user s ...

What is the best way to make an HTML form show fields depending on certain conditions?

Initially, I created an index page containing a form with various fields. The utility was built to handle all the fields, but now there's been a change in requirements. What I need is for only the Controller Type and Test Type fields to be displayed f ...

jQuery's feature to select all elements except one and its children appears to be malfunctioning in Safari

My goal is fairly simple. I want to make the entire section clickable, except for the span and anything beneath it, so that the link redirects elsewhere. <section id="id" class="message"> <div class="message_body"> <font color="color"> ...

How to combine two tables in Sequelize using a one-to-many relationship

I'm currently working with two models: User and Foto. In my application, each User can have multiple fotos, and each foto is associated with only one user. My challenge lies in using the include function. I am able to use it when querying for the us ...

AngularJSError

I am completely new to AngularJS and I've been tasked with debugging someone else's code. While debugging in Google Chrome, I encountered the following error: TypeError: accountService.logIn(...).success is not a function. The issue lies with ...

Initiate a $digest cycle externally

How can I ensure that $digest triggers when calling methods from outside Angular in an application where code is loaded and eval'd at runtime? Considering that these methods may also be called from within Angular, would it be better to expose a separa ...

Is there a way to trigger the second function once the first one has been completed?

When the change event occurs, I am invoking two functions. function1(); function2(); The function1() makes an ajax call. The function2() is running before function1() for some reason. Can anyone explain why this is happening? Any assistance would be ...

The current status of the ajax call is set to 0

I am currently attempting to retrieve information from a remote server on my local machine. The readyState seems to be fine, equal to 4. However, the status is consistently showing as 0 instead of 200. When I click the button, it doesn't return anythi ...

Multipart form data processing without specifying files

I need help with uploading an image using node.js, express, and multiparty. My code is as follows: HTML <!DOCTYPE html> <html> <body> <form method="post" action="/img"> Select image to upload: <input type="file" name= ...

"Transferring a JavaScript variable to Twig: A step-by-step guide for this specific scenario

When it comes to loading a CSS file based on the user's selected theme, I encountered an issue while trying to implement this in my Symfony application using Twig templates. The code worked flawlessly on a simple HTML page, but transferring it to a Tw ...

Searching for the XPath of a specific file selection button can be done easily by using

I have been attempting to click on the "Select file" button, but so far, the XPath I used has not been successful: driver.findElement(By.xpath("//div[@class='ant-modal-body']//button[contains(@class,'ant-btn-ghost')]/i")).click(); Unf ...