Is it necessary to click the button that is visible in Protractor?

I am working on a wizard page that consists of multiple steps. Each step is shown based on the value of the "step" scope variable:

<div ng-show="step == 'first'">
  <button>Next</button>
</div>

<div ng-show="step == 'second'">
  <button>Next</button>
</div>

<div ng-show="step == 'third'">
  <button>Next</button>
</div>

However, I am facing issues when trying to click the next button as there are three buttons with the same text. When using the following code:

var next = element(by.buttonText('Next'));

All three buttons are identified by this code. How can I locate and click only the visible button?

Answer №1

At first, the concept of isDisplayed returning a promise was a bit confusing to me. After some brainstorming, I managed to come up with the following function:

function selectOption(value) {
    var options = element.all(by.value(value));
    options.each(function(option) {
        option.isDisplayed().then(function(isVisible) {
            if (isVisible) {
                option.click();
            }
        })
    });
}

This function can be utilized in the following manner:

selectOption('yes');

Answer №2

If you want to improve the readability of your code and make sure a single visible button is clicked, consider using the filter() method:

function clickVisibleButton(text) {
    var buttons = element.all(by.buttonText(text));
    var visibleButton = buttons.filter(function(button) {
        return button.isDisplayed().then(function(isVisible) {
            return isVisible;
        });
    }).first();
    visibleButton.click();
}

This approach will also throw an error if no visible buttons are found, providing better error handling compared to your current method.

Answer №3

If you need to target specific next buttons, you can chain the elements accordingly in your code.

var firstStepNext = element(by.css('div[ng-show="step == \'first\'"]')).element(by.buttonText('Next'));

var secondStepNext = element(by.css('div[ng-show="step == \'second\'"]')).element(by.buttonText('Next'));

var thirdStepNext = element(by.css('div[ng-show="step == \'third\'"]')).element(by.buttonText('Next'));

// Click the next button on the first step
firstStepNext.click();

// Click the next button on the second step
secondStepNext.click();

// Click the next button on the third step
thirdStepNext.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

Using Express.js to import a SQL file

I am facing challenges while attempting to import an sql file into Express JS. I have tried various codes involving the mssql and fs modules, but none seem to be working as expected. fs.readFile(__dirname +'/database.sql', function (err, sqlFile ...

Ways to monitor and measure clicks effectively

Within my website, I have a table element with one column and numerous rows. Each row serves as a hyperlink to an external shared drive. <tr><td ><a href="file://xxx">Staff1</a></td></tr> <tr ><td ><a h ...

Can you retrieve functional context from a class component in react-native?

In my current react-native project version 0.63.2, I am implementing @react-navigation-5 for navigation. The navigation flow includes transition from the splash screen to the login screen and then to the tab screen all done using context. appContext.js im ...

Enhancing the current Node.js, Express, MongoDB, and Socket.io stack with the integration of AngularJS

After spending some time developing a web app using Node.js, Express, MongoDB, Mongoose and Socket.io, I've successfully released version one. Looking ahead to version two, my plan is to revamp the UI completely and switch to a front-end framework lik ...

Using Google Maps: Dragging the marker constantly results in the same position being returned by GetPosition

I'm having an issue with a for loop that creates more than 100 markers. Every time I drag a random marker, the console logs the same position even though the "Point" value is different when dragging another marker. Why am I consistently getting the sa ...

Instructions on utilizing the initialized Webdriver instance from the Base class in a child class in Java

public class Base { public WebDriver driver; @BeforeMethod public void setUp() { driver = new FirefoxDriver(); } } public class CustomFunctionality extends Base { public CustomFunctionality(WebDriver driver) { ...

Issue with AngularJS: Not able to get second app in template to function properly

I have encountered a puzzling issue with my two nearly identical apps. The first one seems to be running smoothly as expected, while the second one doesn't appear to be executing at all. Here is my code (jsfiddle): <div ng-app="passwdtool" ng-con ...

Creating custom generic functions such as IsAny and IsUnknown that are based on a table of type assignability to determine

I attempted to craft a generic called IsAny based on this resource. The IsAny generic appears to be functioning correctly. However, when I implement it within another generic (IsUnknown), it fails: const testIsUnknown2: IsUnknown<any> = true; // iss ...

The javascript dropdown feature functions properly on jsfiddle, but is not working in an HTML document

I am attempting to populate a dropdown menu with minutes using JavaScript. Although it works in this JSFiddle, the code does not function properly when I try to implement it on my own page. Below is the code snippet: <html> <head> ...

Fulfill the promise once all images have finished loading

When I was preloading images, my initial code looked like this: function preLoad() { var deferred = $q.defer(); var imageArray = []; for (var i = 0; i < $scope.abbreviations.length; i++) { imageArray[i] = new Ima ...

Issue with verification code for form with changing text color

I've been working on a form that collects an email and password, then checks if the email is valid by ensuring it contains an "@" symbol. If the email doesn't contain "@", the paragraph tag with the title "email" should change color. However, des ...

Is there a way to retrieve the parameters of a function that I am passing as an argument to another function?

As I strive to retrieve the arguments from the function passed as a parameter in order to ensure they are properly forwarded, an error has emerged: TypeError: 'caller', 'callee', and 'arguments' properties may not be access ...

From PHP to JavaScript, the looping journey begins

Question I am attempting to display markers on a map using PHP to fetch the data, then converting it into JavaScript arrays for marker addition. Below is an example of my code: Database query require_once("func/connect.php"); $query = "SELECT * FROM sit ...

combine 2 documents

Two HTML files are on my hands. Both of these HTML files need to be combined. Is there a method in JavaScript or Jquery that can merge two files into one? I have looked at the append and other functions in Jquery, but I am dealing with two large files. ...

Interact with an AngularJS model using an external script

I've exhausted all possible methods to activate the ng-model functions in my form. Utilizing the bootstrap datepicker, I need the ng-model value to update when a date is selected. Can someone please advise me on how to interact with the ng-model using ...

Is there a way for me to determine if the HTML code is creating a new line?

Here is my code snippet: <div id="box"> <p> 123 </p> <p> abc </p> </div> <script> var html = document.getElementById("box").innerHTML; for (var i = 0, len = html.length; i & ...

In anticipation of a forthcoming .then() statement

Here is a return statement I have: return await foo1().then(() => foo2()); I am wondering, given that both foo1 and foo2 are asynchronous functions, if the code would wait for the resolution of foo2 or just foo1? Thank you. ...

Transferring properties from React Router to child components on the server side

For my Isomorphic app using React, react-router v3, and material-ui, it's crucial to pass the client's user agent to the theme for server-side rendering. This is necessary for MUI to properly prefix inline styles. Initially, the root component o ...

Selenium is experiencing crashes when attempting to upload images in Chrome. What steps can be taken to resolve this

I am automating the mobile Chrome browser on an Android phone using Selenium and Appium. I have successfully connected a real Android device through adb connect {ip address of mobile} All test cases on the Android Chrome browser run smoothly, except fo ...

Delivering JSON and HTML safely to JavaScript applications

As I brainstorm secure methods for delivering HTML and JSON to JavaScript, my current approach involves outputting JSON in this manner: ajax.php?type=article&id=15 { "name": "something", "content": "some content" } However, I am aware of the ...