Improving efficiency in protractor click tests by implementing For-Loops

Query: How can I successfully click on each link within a ul > li a in one single test?

Issue: Although the test is currently passing, it is not effectively clicking on the links. This can be verified by the absence of redirection or the expected 2000ms delay.

Test Scenario:

  it("should navigate to all footer links correctly", function() {
      browser.driver.sleep(2000);
      browser.ignoreSynchronization = true;
      //creates an array containing the text of all menu items
      var titles = element.all(by.css('.leftMenu.first .submenu li a'))
          .map(function(elm) {
              return elm.getText().then(function(text){
                 return text;
              });
          });

      //iterates through the links using the titles array
      for (var i = 0; i < titles.length; i++) {
          // creates a link by selecting the element that contains the text from the titles array
          var link = element(by.cssContainingText('.submenu li a', titles[i]));

          //click functionality
          link.click().then(function() {
              browser.driver.sleep(2000);
              //current expectation may seem arbitrary but should pass
              expect(browser.driver.getTitle()).toBe('welcome to: ' + title[i]);
          });

      }

  });

UPDATE: Solution found here: ANSWER

Answer №1

After reviewing the previous suggestions, I noticed a common 'synchronous' approach being taken. Allow me to introduce my solution to the same problem, which utilizes the standard asynchronous protractor method.

For instance, in this scenario, the footer contains text links such as 'ABOUT', 'CONTACT', etc., each corresponding to URLs like '/about' and '/contact'.

Note: The variable ptor is initialized earlier using protractor.getInstance();

it('should have functioning internal page links in the footer', function() {
  // element.all( -your selectors- )
  // .then() receives an ARRAY of element finders 
  element.all(by.css('.footer .nav .links')).then(function(elems) {

    // Each element's .getText() returns a promise
    var txts = elems.map(function(elem) {
      return elem.getText().then(function(txt) {
        if(txt != ''){
          return txt;
        }
      });
    });

    // txts is now an ARRAY of promises
    // Upon fulfillment of all promises, the following loop executes
    protractor.promise.all(txts).then(function(links) {
      for (var i=0; i<links.length; i++) {
        // Reset browser back to the main page
        browser.get('/');

        // Obtain a fresh element instance and click on it
        // Clicking on pre-existing elements may lead to 'stale' references
        // due to navigation between pages
        element.all(by.css('.footer .nav .links')).get(i).click();

        // Verify the expected navigation
        expect(ptor.getCurrentUrl()).toContain(links[i].toLowerCase());
      }
    });

  });

});

Answer №2

REPEAT: RESPONSE AVAILABLE HERE

To ensure synchrony, enclose the it block in an IIFE (Immediately Invoked Function Expression)

for(var j=0; j < testParams.length; j++) {

    (function(testCase) {
        it('insert your test here', function() {
            //test code goes here
        }
    })(testParams[j]);

};

Answer №3

The primary issue at hand is:

return elm.getText;

getText is actually a method that returns a promise. Therefore, what you really need to do is something more along the lines of

return elm.getText().then(function(text){
    return text;
});

When you invoke a method such as getText or getInnerHtml, it simply gives back a promise. In case you want the value after the promise has been resolved, you must use then to chain and retrieve the value.

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

Is it possible to use a += operator with attr() and val() functions in JavaScript?

Ever since I switched to jQuery, my development process has significantly sped up. However, there is one task that has become a bit more time-consuming: appending a string to an attribute or value. For instance, if you wanted to add a letter to the value ...

Is there a way to increase the size of the icon without altering the dimensions of the button?

After implementing a code snippet to enable a button to copy the URL to the clipboard, I encountered an issue. Originally, the button displayed the text "copy," which changed to "copied" after clicking on it and reverted back after 2 seconds. However, I d ...

Why are cloned jQuery elements triggering events on the parent <div> and not the child <div>?

Currently, I am working on a tool that includes dynamic input fields for user input. To create different sections, I have cloned some divs from the code successfully. However, I am facing an issue where the events attached to the parent div are triggered e ...

The dynamic form is programmed to display identical values for both the initial and subsequent inputs

Currently, I am developing a personalized dynamic form utilizing the Material UI library as the component for my React Js application. You can find more information about this library at https://mui.com/. In front of you is the initial setup of the dynami ...

Are the Div Tags displaying in a vertical alignment instead of a horizontal one?

I have 3 div elements, each with a width of 4. I want to align them all in a row but I am also using a toggle button to show these divs because by default their display is set to none. When the user clicks the toggle button, the divs will be shown to them. ...

Show the loader animation until the browser's loading icon stops spinning

My website receives a high volume of traffic and pulls data from several servers to display on the page. It typically takes 3-4 minutes for the entire page to finish loading. Here is a preview of some of the partial page data: https://i.sstatic.net/br4sr. ...

Changes in query parameters on NextJS navigation within the same page do not activate hooks

When utilizing NextJS without SSR, I encountered an issue with basic navigation using different query parameters. Upon the initial arrival on the page/component, everything seems fine as the component gets mounted and URL params change accordingly. However ...

Having issues with executing promises within map function in JavaScript

I am currently working on a JavaScript function that handles API calls within a map method. However, before completing all the tasks within the map method, my function is producing incorrect results. It is not meeting my expectations. Here is the code sni ...

Detecting URL changes, excluding just the hash, with JavaScript/jQuery

It's interesting to note that some websites are built using a "one-page system". In this type of system, when a user clicks on a link, the site doesn't take them to a new page but instead reloads the existing page with Ajax and updates the URL. ...

Execute the jQuery function to submit the form via AJAX once the validation process has been

I am currently working on a form and implementing the jQuery validate plugin for validation purposes. My aim is to trigger the ajax code to submit the form only after the validation process is successfully completed. How can I achieve the following: // T ...

Utilizing displacement mapping in three.js

Currently, I am using a grayscale image as a bump map for my model. The model consists of an .obj file paired with the corresponding .mtl file for UV mapping. Below is the code snippet that I am utilizing: // Load material file var mtlLoader = new THREE.M ...

Using Knockout to bind an element to the selected value from a dropdown list

When using the following select, I am connecting it to an observable array. <select id="selectProtocols" data-bind="options: optionsAvailable, optionsCaption:'Selecione...', optionsText: 'SimpleDescription', optionsValue:'???&a ...

Executing a Javascript function post AJAX page loading

I'm not a coding expert, so I hope my question is still clear. Essentially, I have an index.php page with filters (by project, year, month) that send variables to filterData.php after clicking submit. These variables are then used in SQL statements t ...

What is the most effective method for embedding a Kotlin program into a website?

I have created a combat simulation tool in Kotlin for an online gaming community. Users can input the combat levels of two players, choose the number of duels to simulate, and then initiate the simulation which will provide win percentages and other stats. ...

Encountering a 'MODULE_NOT_FOUND' error when using the Svelte `node scripts/setupTypeScript.js` command

I encountered a problem in my Svelte project: Although my files display no errors in VSCode, when I run npm run dev --, all Typescript syntax is flagged as erroneous, and the server fails to start. To address this issue, I attempted removing all node_mod ...

express middleware is not compatible with prototype functions

I've encountered a perplexing issue while working with the node.js express framework. Let's say I have a file called test.js containing the following code: function a(){ } a.prototype.b = function(){ this.c("asdsad"); } a.prototype.c = f ...

Difficulties encountered when launching a Meteor app with React using static-html

I'm currently working on a project that uses the Meteor framework along with React. When I attempt to start the application using the npm start command, I keep encountering errors related to static-html files. As a newcomer to Meteor, I've attemp ...

Type of Angular Service Issue: string or null

I'm encountering a persistent issue with my Angular code, specifically while calling services in my application built on Angular 13. The problem arises when trying to access the user API from the backend, leading to recurrent errors. Despite extensive ...

MUI options - The specified type 'string' cannot be matched with type '"icon" | "iconOnly" | "text" | "outlined" | "contained" | undefined'

Is it possible to utilize custom variants in MUI v5? I am having trouble using a custom variant according to their documentation: https://mui.com/material-ui/customization/theme-components/#creating-new-component-variants declare module "@mui/material ...

I'm receiving an error code 500 when attempting a patch request on my Express backend - what's causing this issue

Whenever my angular frontend sends a patch request to my express backend, all routes work smoothly except for the patch routes. The specific error message that pops up is: Error: No default engine was specified and no extension was provided. Should I be ...