Protractor never-ending cycle

In my previous question, I encountered an issue with clicking a button until it becomes disabled. Initially, the solution was as follows:

var nextPage = function () {
    if (element(by.css('[ng-click="vm.nextPage()"]')).isEnabled()) {
        element(by.css('[ng-click="vm.nextPage()"]')).click();
        nextPage(); // proceed to next page
    }
    else {
        return; // button is disabled, reaching last page
    }
}

However, I had to make some adjustments to the code and now it looks like this:

 var nextPage = function() {
  if (element(by.id('next')).isEnabled()) {
    element(by.id('next')).click().then(function() {
      browser.sleep(1000);
      nextPage(); // proceed to next page
      return;
    });
  } else {
    return; // button is disabled, reaching last page
  }
  return;
}

Unfortunately, this modification resulted in infinite recursive calls, making it impossible to perform the next step. I tried removing the .then function but then the code stopped working altogether. How can I correct this without causing endless recursion?

Answer №1

The issue lies in the fact that the recursion base case is never satisfied, causing the recursion to continue indefinitely.

It is important to keep in mind that every aspect of protractor operates as a promise, and in your specific scenario, isEnabled() is an unresolved promise which always evaluates to "truthy". This results in the loop continuing regardless of the actual value of isEnabled, leading to the error of reaching the maximum recursion depth.

To obtain the true boolean value of isEnabled, you need to explicitly resolve the promise:

element(by.id('next')).isEnabled().then(function (isEnabled) {
    if (isEnabled) {
        // ...
    } else {
        return; // the element is not enabled, indicating the last page
    }
});

On a related note, it's worth mentioning the shameless promotion of a tool that could have detected this issue sooner - the eslint-plugin-protractor along with its rule that identifies protractor promises being used directly within if conditions without explicit resolution. The output of this detection tool when applied to code similar to what was included in the original question would look like this:

$ eslint test.js
/path/to/test.js
  2:5   warning  Unexpected "isEnabled()" inside if condition  protractor/no-promise-in-if 
  4:13  warning  Unexpected browser.sleep()                    protractor/no-browser-sleep

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

Update the router URL without switching pages, yet still record it in the browser history

One of the features on my search page allows users to perform searches and view results. Initially, I faced a challenge in updating the router URL without navigating, but I managed to overcome this by utilizing the "Location" feature. In my ngOnInit meth ...

Encountering an issue in XtermJS where it is unable to read properties of undefined, specifically 'dimensions', while being used with NextJs version 14

UPDATE: Additional Details useEffect(() => { // let terminal; if (terminalRef.current) { const terminal = new Terminal({ fontFamily: "Menlo, Monaco, monospace", // fontSize: 12, // cursorBlink: true, ...

Ways to set the initial value of an input[range] in Angular2 when the value exceeds 100

After encountering a similar issue with AngularJS, I posted a question on StackOverflow titled How to initialize the value of an input[range] using AngularJS when value is over 100. As I dive into learning Angular2, I am curious if it handles initializatio ...

How can I protect my jQuery script from being accessed by "FIREBUG"?

I was tasked with creating a jQuery script as follows: function DeleteFile(_FileID) { //ajax method to delete the file } The FileID is stored in the 'rel' attribute of the list. However, when I call "DeleteFile" from Firebug using the fileId ...

Execute function after AngularJS returns data

My dilemma revolves around calling a callback function while struggling to retrieve the necessary data due to an error in my method. Here is what I have attempted: //function with callback filterList: function(type, cb) { if (type == 'all') { ...

When I open my website in a new tab using iOS and Chrome, the appearance of the absolute element is being altered

I am experiencing an issue with a div that is positioned absolutely at the bottom left of my website. When I open the site in a new tab using <a target="_blank" href="./index.html">, the bottom value is not being applied correctly ...

Guidelines for capturing a div screenshot with javascript

Let's say I have a div containing an image source. <div> <p class="row">With custom CSS</p> <img src="/images/midhun.jpg"> </div> When a button is clicked, I want to display a screenshot of this image in another div. C ...

Trouble retrieving desired data from an array of objects in React Native

I'm having trouble retrieving values from an array of objects in my state. When I try to access the values, it only prints out "[Object Object]". However, when I stored the values in a separate array and used console.log, I was able to see them. Here ...

Scrolling through a list while the user types in the search bar

I am currently working on a table that populates based on an array of country objects, and I have added a search bar to enable live filtering through the countries array. However, as a newcomer to Vue, I am struggling to implement this feature effectively. ...

How come defining the state using setTimeout does not display the accurate properties of a child component?

Presented here is a component designed to render a list of items and include an input for filtering. If no items are present or if the items are still loading, a message should be displayed. import { useState } from "react"; export const List = ...

Encountering a Typescript TypeError in es2022 that is not present in es2021

I'm attempting to switch the target property in the tsconfig.json file from es2015 to es2022, but I am encountering an error while running tests that seem to only use tsc without babel: Chrome Headless 110.0.5481.177 (Mac OS 10.15.7) TypeError: Can ...

When attempting to run Protractor, an error occurs indicating that the module '../built/cli.js' cannot be located

Due to an issue present in Protractor 3.3.0 with getMultiCapabilities, we had to install the latest version directly from GitHub where a fix has been implemented (refer to the fix scheduled for Protractor 3.4). To include this fix, we updated our package. ...

An issue has occurred while utilizing Angular

I'm diving into the world of Angular and encountering some errors as I try to execute this code. An unexpected token is causing trouble. A constructor, method, accessor, or property was expected. The left side of a comma operator seems to be unused ...

tips for accessing the useState value once it has been initialized

When using the state hook in my code, I have: const [features, setFeatures] = useState([]) const [medicalProblem, setMedicalProblem] = useState([]) The medicalProblem variable will be initially populated with a response from an API call: useEf ...

Array of dynamically typed objects in Typescript

Hello, I am a newbie to Typescript and I recently encountered an issue that has left me stumped. The problem I am facing involves feeding data to a Dygraph chart which requires data in the format [Date, number, number,...]. However, the API I am using prov ...

The search box implemented in the navbar of AngularJS retrieves data to display in a table

Hey there! I'm trying to filter a table of data using a navbar search box located outside the view where the table is displayed. Struggling to figure out how to make this work. Here's the code snippet for the search box inside the navbar: <di ...

Rendering user actions instantly in React.js without waiting for server propagation

I am currently developing a shopping list web application where users can toggle items as 'checked' or 'unchecked'. The flow of data in this application is as follows: click on item checkbox --> send database update request --> ...

Exploring the power of TypeScript for authenticating sessions with NextJS

Utilizing next-auth's getSession function in API routes looks something like this for me: const mySession = await getSession({ req }); I have confirmed that the type of the mySession is outlined as follows: type SessionType = { user: { email: s ...

Having issues with the forEach and map functions not iterating through every item in an async-await function in Vue.js?

My orders array contains a number of meal plans, each with items inside. I'm trying to process all orders as paid in the inner loop when I click on place orders. However, the code is only processing some and leaving others behind. Below is my implem ...

Tips for unit testing an Angular Service that is primarily responsible for redirecting to an external page from the application

My service is responsible for redirecting to a separate login page since we are implementing login as a service. function redirectToMembership() { var returnURL = $location.host(); returnURL+="/#/Authorization"; $window.location.href=Environme ...