Can we leverage protractor's by.cssContainingText for dynamic text conditions?

I am looking for a way to conditionally change text content in my web project, but I'm facing a challenge since the conventional methods seem limited. The cssContainingText function typically accepts string or regular expression values. Is there a workaround that would allow me to use it dynamically based on certain conditions?

The code snippet below serves as a demonstration of my scenario.

let text;

if (a){
  text = 'John Doe is a name';
} else if (b) {
  text = 'Hello world';
} else if (c) {
  text = 'This is a whole new sentence';
} else {
  text = 'Default text'
}

return <div className='my-text'>{text}</div>;
element(
    by.cssContainingText(
      'my-text',
      ["/*Insert logic for conditional*/", ],
      // even something like, 'text' || 'text-2' || 'text-3'
    ),
  );

Answer №1

The most convenient approach would be to utilize ExpectedConditions and simply wait for the element to appear on the screen. Essentially, perform any actions that will trigger the text to change, and then wait for that specific element to become visible. There are two ways you can tackle this - either specify all the expected elements on the page, or create a function where you input the desired text and wait for it to load. The examples below assume that you have previously defined EC and a customized waiting time elsewhere in the class.

const someText = 'my sample text';
await waitForElementWithText(someText);
// proceed with other tasks once the element is visible

....

async function waitForElementWithText(waitForText) {
  const elem = element(by.cssContainingText(waitFortext));
  return browser.wait(EC.visibilityOf(elem), myWaitTime);
}

If you need to interact with the element after waiting for it to load, simply define the element and pass it into the waiting function

const elem1 = element(by.cssContainingText('my sample text');
const elem2 = element(by.cssContainingText('my other text');

// perform actions that make elem2 visible

await waitForElementVisible(elem2);
// now you can engage with elem2

...

async function waitForElementVisible(elem) {
  return browser.wait(EC.visibilityOf(elem), myWaitTime);
}

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

Issue with karma-ng-html2js-preprocessor failing to generate modules

Struggling to configure the karma-ng-html2js-preprocessor. While Karma has been successfully detecting all my JavaScript files, it's having trouble generating a module from the HTML preprocessor. Take a look at my options object below. I've spec ...

Is there a way in Bower to automatically select only CSS or JS files from an open source project, rather than both, if that is my preference?

Although I suspect the answer, imagine I desire to incorporate the CSS from Twitter Bootstrap without the Javascript. I've set up a gulp script to extract everything from my bower.json file, minimize the JS, compress the CSS, and transfer it to my de ...

Utilizing jQuery to extract the id and update its content

One of my tasks involves working with a table generated by PHP and incorporating a modal that allows users to change the text produced by the variable $l_id. I have a link with a class "eloc" that triggers the display of the modal div section. By intercept ...

Having trouble loading a chart with amcharts after sending an ajax request

I have integrated amcharts to create a pie chart. When I click a button, an AJAX request is triggered to fetch data from MySQL in JSON format. After receiving the JSON array, I pass the data to amcharts but the chart doesn't display. Oddly, if I redi ...

Using Express and Node.js to display a page populated with information

On my webpage, I currently have a list of Teams displayed as clickable links. When a link for a specific Team is clicked, the Key associated with that Team is extracted and sent to the /team/:key route to retrieve the respective data. If the data retrieval ...

JavaScript Indexed Array Names: Managing Arrays with Indices

I have a collection of arrays named "list0" through "list7" which have been explicitly defined. My goal is to include each of these arrays as elements in an existing array, creating a 2D array of these defined arrays. How can I reference each 'list&a ...

Animating CSS Pixel Fragments

After applying a simple CSS animation that moves size and box shadows from one side of the screen to the other, I am noticing residual pixel fragments left behind. To see this issue in action on Chrome 66, check out the Code Pen: https://i.sstatic.net/Gl ...

JavaScript Alternatives for jQuery Functions

Currently in the process of eliminating the jQuery dependency from my AngularJS project, I encountered the following code as part of a spec within my codebase: beforeEach(inject(function($rootScope, _$compile_) { scope = $rootScope; $compile = _$c ...

Having trouble identifying whether a file is a picture or video based solely on its extension

My current challenge involves determining whether an uploaded file is a video or a photo. This distinction is crucial as it dictates whether the file should be sent to my telegram bot as a video or photo attachment. Despite having what seems like a logica ...

How can I ensure a function only runs after all imports have been successfully loaded in Vue 3?

Encountering an issue with importing a large quantitative variable in Vue 3. Upon running onMounted, it seems that the import process is not yet complete, resulting in an error indicating that the variable tesvar is "uninitialized". The code snippet prov ...

Implementing a global custom header in AngularJS for all HTTP requests

Is there a way to set custom information in the headers for all $http requests without having to repeat the same configuration for each call? For example: var config = {headers: { 'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5 ...

Node.js poses a challenge when it comes to decoding incoming request data

I am attempting to create a sample login page using the combination of node, express, and angularjs. Displayed below is my login view: <div class="login-page"> <div class="login-page-content"> <div style="margin-top:30px;padding:10px;w ...

"RecognitionAudio variable missing" and "InactiveRpcError occurred" [Utilizing the Google text-to-speech API]

I have a goal I'd like to achieve. A user communicates with a web browser. The web browser records the user's voice as a WAV file using Recorder.js and sends it to a server running on Google App Engine Standard environment with Python 3.7. The ...

While attempting to deploy my project on Vercel by pulling in my code from GitHub, I ran into this error

As a self-taught Front End developer diving into building and hosting my first web page using React, I've encountered this warning. Any suggestions on how to resolve it? Cloning gitohub.com/Passion94/React-Apps (Branch: main, Commit: da89a2a) Cloning ...

What is the best way to search through directories for JSON files in JavaScript?

I am looking to navigate through directories to find json files and combine them all into a single json file for each directory. I consider myself a beginner in javascript. The javascript code should be executed by calling it in the Terminal, instead o ...

The div reveals a submenu by popping out when its overflow is set to hidden

I am trying to figure out how to create a horizontal menu with sliding option and submenu. The issue arises when I set overflow to hidden for the sliding effect, as it causes problems with the submenu. Any suggestions or ideas on how to solve this dilemma ...

Troubleshooting: Issue with Bootstrap 4 navbar toggle button functionality

Is it possible to manually control the opening and hiding of the navbar when the toggle button is clicked in bootstrap 4? Currently, my navbar automatically opens and closes when clicking the toggle button. Any suggestions on how to modify this behavior wo ...

Choosing the Laravel 6 option for editing via AJAX: A step-by-step guide

I am looking to update a user who resides in a specific state within a country. The country and state fields are dropdown select options, with a relationship established between them and the user. The state field is populated based on the selected country. ...

Send query string parameters to retrieve data within a specific updatedAt timeframe

How can I retrieve data based on a specified range of month/week/days it was last updated? this.userDetails = async (req) => { try { let updatedAt = req.query.updatedAt let start = moment().startOf('day') let end = ...

How to programmatically unselect an ng-checkbox in AngularJS when it is removed from an array

Utilizing checkboxes to gather values and store them in an array for dataset filtering purposes. The objectives are as follows: Show child filters when parent category is selected. Unselect all children if parent is unselected (otherwise they will ...