I make a commitment to continue working until the issue is resolved and the page is successfully changed in the Protractor

I have a table with rows and I need to click on the edit button in a row that has a specific label (test server label).

This is my function:

public selectOnRow( textSelector:string , clickableSelector : string , value:string) {
    let promise = new Promise(resolve => {
        element.all(by.css(textSelector)).each((elem, i) => {
            elem.getText().then(function (text) {
                if (text === value) {
                    resolve(i);
                }
            });
        });
    });
    promise.then(i => {
        element.all(by.css(clickableSelector)).get(i).click();

    })
}

And this is how I am using it:

beforeAll(async () => {
            page = new AppPage;
            page.navigateTo('/asset/server');
            page.selectOnRow('.column-label div', '.edit-action-btn', 'test server label')
            baseUrl = page.baseUrl;
        });

The problem arises when the page changes - the selectOnRow function continues to loop through rows that are no longer on the current page. This results in the following error:

Failed: stale element reference: element is not attached to the page document

Answer №1

Utilizing the filter function in ElementFinderArray

An interesting way to leverage the filter function is by using it with element.all. This function adds elements that satisfy a certain condition to an ElementFinderArray, which is the same type of object returned by element.all.

Performing a click action on selected elements

In this scenario, we set an index variable when a specific text matches. The index value is only set if it's empty. We then wait for the filter function to finish executing before clicking on the element specified by the clickableSelector with the determined index value.

Handling asynchronous methods with await

To ensure proper execution, it's important to return the entire promise for selectOnRow. This allows you to invoke the function using

await selectOnRow(textSelector, clickableSelector, value);

Snippet of the provided code

public selectOnRow(textSelector: string, clickableSelector: string, value: string) {
    let index: number;
    return element.all(by.css(textSelector)).filter((elem, i) => {
      return elem.getText().then(text => {
        // Check if index is not assigned
        // If text matches, update the index
        if (!index && text === value) {
          index = i;
        }
        return text === value;
      });
    }).then(() => {
      // Wait for the filter function to complete
      // At this point, the index should be initialized
      return element.all(by.css(clickableSelector)).get(index).click();
    });
}

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

Vue: Simple ways to retrieve state data in MutationAction

I'm having trouble accessing the state inside @MutationAction Here is the setup I am using: Nuxt.js v2.13.3 "vuex-module-decorators": "^0.17.0" import { Module, VuexModule, MutationAction } from 'vuex-module-decorators' ...

Using React's higher order component (HOC) in TypeScript may trigger warnings when transitioning from non-TypeScript environments

I have a simple HOC component implemented in React with TypeScript. export const withFirebase = <P extends object>( Component: React.ComponentType<P> ) => class WithFirebase extends React.Component<P> { render() { return ...

Encountering TypeScript error TS2345 while attempting to reject a Promise with an error

I recently encountered a perplexing TypeScript error message that I am struggling to comprehend. The specific error reads as follows: error TS2345: Argument of type '(error: Error) => void | Promise' is not assignable to parameter of type & ...

What is the best way to trigger a function in the parent component when a child component is clicked

I'm facing a scenario where I have two components - a parent and a child. Within the child component, there is a button. My goal is to trigger a method in the parent component when the user clicks on that button within the child component. Any ideas o ...

Keep displaying the default angular loading screen until the angular2 router is fully resolved

Angular2 CLI has a default loading screen that displays until the app gets bootstrapped with <app-root>Loading...</app-root>. Once this is done, the Angular2 route resolver makes an API call to verify whether the user is authenticated before n ...

Retrieve data that resets to undefined upon reloading from an array

Encountering an unusual error while working with TypeScript for the first time. Initially, when I use console.log(data), it displays an array with objects. However, upon reloading the webpage without making any changes, the console log shows undefined. con ...

User interaction with a checkbox triggers a state change in Angular

Here is the code snippet I am working with, where clicking should set the checked value to false: @Component({ template: ` <input type="checkbox" [checked]="checked" (change)="onChange()"> ` }) export class AppC ...

Fire the BehaviorSubject with the identical value following a mutation

I am working with a BehaviorSubject where I have to make changes through mutation (for reasons beyond my control). I need to trigger the BehaviorSubject for subscriptions whenever there are changes. Is there another approach I can take instead of using: ...

Authenticate the digital signature created with the ED25519 algorithm

My current task involves verifying a digital signature that was signed using ED25519 with typescript Crypto, but I need to verify it in Java using BouncyCastle. The code snippet I am using for verification is as follows: byte[] decodedSign = Base64.getDeco ...

Angular Pipe -- Implicit type 'any' error occurs when trying to index type 'string' with an expression

Encountering an error while constructing the time ago pipe: Obtaining an implicit 'any' type due to inability to index type with a 'string' expression if (value) { const seconds = Math.floor( (+new Date() - +new Date(Numb ...

Retrieve the callback arguments using sinon.spy within a JavaScript promise

During my test with mocha and sinon, I encountered an issue where I couldn't retrieve a callback value from inside a promise scope of an HTTP-request due to the asynchronous nature of promises. It seems that by the time sinon.spy checks on the callbac ...

What is the process for transforming a string literal type into the keys of a different type?

Imagine having a string literal type like this: type Letters = "a" | "b" | "c" | "d" | "e"; Is there a way to create the following type based on Letters? type LetterFlags = {a: boolean, b: boolean, c: bool ...

Utilizing TypeScript namespaced classes as external modules in Node.js: A step-by-step guide

My current dilemma involves using namespaced TypeScript classes as external modules in Node.js. Many suggest that it simply can't be done and advise against using namespaces altogether. However, our extensive codebase is structured using namespaces, ...

ng-select issue: list not refreshing

I am encountering an issue with the method below that updates the modules array. Even though the console displays the result correctly, the ng-select does not update the list accordingly. I attempted to use this.modules=[...elements], but it did not work ...

What is the best way to ensure type safety in a Promise using Typescript?

It seems that Promises in Typescript can be type-unsafe. This simple example demonstrates that the resolve function accepts undefined, while Promise.then infers the argument to be non-undefined: function f() { return new Promise<number>((resolve) ...

Guide to implementing an "export default" with various types and values in a TypeScript module

There is a simple way to export multiple values as default: class Car {...} class Bus {...} export default { Car, Bus } You can also easily export a type as default export default interface Airplane {...} However, exporting multiple types as default i ...

Does this fall under the category of accepted practices for employing an effect in Angular?

I am working on integrating an Angular directive with a signal that receives values from a store selector. This signal is crucial for determining whether a button should be disabled or not. I'm curious about the best approach to listen to this signal ...

What steps should I take in order to correctly implement the onChange event and retrieve the event.target.value in my

Incorporating useForm, yupResolver, and Yup for validation caused issues with the previously functioning handleChange function. The value variable doesn't log anything when console.logged, indicating a disconnect with the input field content. Addition ...

Strategies for managing dependent HTTP service call subscriptions with RxJs operators

In my application, I have implemented a function called fetchSeviceProviders that retrieves a list of service providers and allows me to set the logo for each provider by making a separate API call. Currently, I am using two subscriptions to achieve this f ...

Having trouble with JavaScript's Date.getUTCMilliSeconds() function?

I have a straightforward question for you. Take a look at this Angular App and try to create a new date, then print the number of UTC milliseconds of that date in the console. Can you figure out why it is returning zero? ...