Creating tests in protractor by iterating through different pages

I am facing a challenge in creating a loop to navigate through multiple pages and generate slightly different tests for each page. The asynchronous nature of the task is causing confusion, making it difficult to come up with a solution. When attempting to use a normal loop, the page always ends up being set to the last one in the array. I have experimented with closures in various ways, but unfortunately, nothing has worked so far. Despite finding valuable insights from this question, I am still struggling to make things function as intended.

var bs = new BasicSteps();

describe("Some description", function() {
    var pages = ['/page1', '/page2', '/page3'];

    var i = 0;
    beforeEach(function() {
        bs.navigate(pages[i]);
        browser.sleep(2000);
        i++;
    });

    for(page in pages) {
        // Code for the spec
        it('Some spec', function() {
            // Some code for the tests
            if(page == 1) {
                console.log("page1");
            }
            else if(page == 2) {
                console.log("Page2");
            } 
            else if(page == 3) {
                console.log("Page3");
            }
        });
    }
});

This results in displaying Page3 three times because the loop executes almost instantly. Attempting to implement a closure leads to an obscure error and crashes before any execution takes place.

var funcs = [];

function createfunc(page) {
    return function() {
        // Code for the spec
    });
}

for(var page = 0; page < pages.length; page++) {
    funcs[page] = createfunc(page);
}

for(var j = 0; j < funcs.length; j++) {
    funcs[j]();
}

Answer №1

If you're looking to bypass Protractor's asynchronous promises and create tests in a loop for multiple pages, utilizing a closure can help streamline your process.

When setting up your test loop, consider implementing the following approach:

// Define an array containing objects with page names and URLs
var pages = [{'name': 'page1', 'url': 'someurl.com/page1'},
             {'name': 'page2', 'url': 'someurl.com/page2'}];

describe("Description of test suite", function(){
  function specifyCurrentPage(curPage) {
    describe(curPage.name, function(){
      it('Test case for current page', function () {
        // Write your test logic here
      });
    });
  };

  generateSpecBlock = function(specifyCurrentPage) {
    return specifyCurrentPage;
  }

  var funcCall = generateSpecBlock(specifyCurrentPage);

  pages.forEach(function(curPage){
    funcCall(curPage);
  });
});

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

Server not displaying React Components

Just starting out with React and I'm puzzled why my components won't load. I may have some outdated code lingering around that's causing the issue. Repository URL: https://github.com/04lex/alex-workspace/tree/1da077943681bccba1876165cfd299b ...

"Implementing form validation and AJAX submission for seamless user interaction

I am seeking a solution to validate my form using ajax and then insert it into the database also utilizing ajax. Although, with the current code, validation messages are displayed, it still performs the insertion. The issue I am encountering seems to be ...

I am having trouble with CSS, JS, and image files not loading when using Angular 9 loadChildren

I am facing an issue with loading CSS, JS, and images in my Angular 9 project. I have separate 'admin' and 'catalog' folders where I want to load different components. However, the assets are not loading properly in the 'catalog&ap ...

"Learn how to smoothly navigate back to the top of the page after a specified amount of time has

Just starting out with JS, CSS, and Stack Overflow! I'm currently working on a div box that has the CSS property overflow: auto. Is it possible to make the box automatically scroll back to the top after a certain amount of time when the user scrolls ...

Is it possible to display the content below the row of the clicked element when it is selected?

I am currently working on building a team page similar to the layout at My goal is to create a row of elements that float or display inline, with hidden content revealed beneath each selected element, pushing subsequent rows further down. Unfortunately, m ...

Automatically resizing textures in Three.JS with WebGL

Seeking assistance to overcome a challenge :) I am using Three.JS to showcase high-resolution equirectangular images on a sphere (20000x10000 pixels). Image quality is crucial for my web application, and bandwidth is not a concern. My issue is that ThreeJ ...

What steps can I take to troubleshoot issues when creating a React app?

While attempting to set up a react application using npx create-react-app projectreact, I encountered the following error message: PS C:\Users\ahnaa\OneDrive\Documents\Web Developent\Reaact JS> npx create-react-app project ...

Error: Attempting to access an undefined property ('call') on Next.js is causing a TypeError

Exploring the realms of Next.js and Typescript for a new project! My goal is to utilize next.js with typescript and tailwind CSS by simply entering this command: npx create-next-app -e with-tailwindcss my-project Smooth sailing until I hit a snag trying t ...

"Discovering the method to successfully click on a link that is housed within a font

Can anyone assist me in creating an XPATH to click on a link with the name "Doors"? This is the code I've attempted: driver.findElement(By.xpath(".//a[contains(text(),'Doors')]")).click(); Here is the HTML snippet. I am trying to click if ...

Challenges arise when attempting to authenticate a user with password.js

Currently, I am working on implementing validation using passport.js and ES6. Below is the validation function that I have created: passport.use(new BasicStrategy( function(login, password, callback) { User.findOne({ login: login }).select(&a ...

Using an XMLHttpRequest to obtain a response from a servlet

Running a jetty server to respond to GET requests has been successful so far. When accessing the request through a browser using localhost:8080/sp or 127.0.0.1:8080/sp, the correct data is returned. public void doGet(HttpServletRequest request, HttpServle ...

Doesn't seem like jQuery's .blur() is responsive on dynamically created fields

I am currently designing a login form that includes a registration form as well. Using jQuery, the email field is generated dynamically. The labels are positioned below the fields so that they can be placed inside the field. As the field gains focus or ha ...

Obtain image data from a websocket server built in C# or VB.NET

Just starting out in the world of websockets, I've got a handle on the client-side code (JavaScript makes it easy) But diving into the websocket server side, particularly in c#, is a whole different ballgame. I'm in need of websocket server code ...

A guide on writing a Jasmine Unit Test for addEventListener

I'm struggling with writing a Jasmine unit test for AddEventListener. How can I effectively test if the code for addEventListener is functioning correctly? private static disableScrollingOnPageWhenPanelOpen(): void { window.addEventListener('DOMM ...

Tips for preventing CSS conflicts when incorporating an Angular 6 application into another application

We recently developed an Angular 6 web application and now we want to seamlessly integrate it into one of our client's online store. However, we are facing some CSS conflict issues: For instance: - The webshop is built on Bootstrap 3 while our app u ...

Automatically populate dynamic fields with ajax response

Using auto-fill with an ajax request works well for static fields. For example: $this->registerJs("$(document).delegate('.form-control','change',function(event){ $.ajax({ url: '".yii\helpers\Url::toRoute( ...

Setting up CucumberJs, Protractor, and TypeScript for Ionic2/Angular2 Projects

Having limited knowledge in TypeScript and Angular2, I've been attempting to run cucumber's features using steps written in TypeScript. However, when executing the steps.ts files, I encounter the following error message: [launcher] Running 1 ins ...

Why does the Node promise chain execute .then despite encountering an error?

When a promise chain encounters an error, why does it not execute .then unless the .then references an external method with a parameter? In this particular example, I intentionally throw an error in the promise chain. The first three .then methods do not ...

Combine the jQuery selectors :has() and :contains() for effective element targeting!

I am trying to select a list item element that has a label element inside it. My goal is to use the :has() selector to target the list item and then match text within the label using the :contains() selector. Can I achieve this in a single line of jQuery ...

Even when using module.exports, NodeJS and MongoDB are still experiencing issues with variable definitions slipping away

Hello there, I'm currently facing an issue where I am trying to retrieve partner names from my MongoDB database and assign them to variables within a list. However, when I attempt to export this information, it seems to lose its definition. Can anyone ...