An issue with asynchronous execution in Protractor


I have been using and learning protractor for over a month now.

Despite the documentation stating that Protractor waits for Angular calls to complete (http://www.protractortest.org/#/), ensuring all steps are executed synchronously, I have not found it to be true in my scripts.

Many times, Protractor seems to run ahead, such as when clicking on a link, getting the current URL, and then verifying the URL.

Often, the URL value is stale, indicating that it was not executed after clicking the link. Below is a sample of my code from the page object and corresponding test.

I am looking for suggestions on how to ensure that all test steps are executed in order.

Page Object
this.getSPageLink(){
    return element(by.xpath("//a[@title='S']"));
};
this.getLPageLink(){
    return element(by.xpath("//a[@title='L']"));
};
this.goToSPage = function() {
    (this.getSPageLink()).click();
    *//ERROR here, sometimes second click (below) doesn't wait for first 
    click to complete, and complains that link for 2nd click (below) is 
    not   found*
    (this.getSLPageLink()).click();
    return browser.currentURL();
    *//ERROR HERE url line (e) is sometimes executed before*
}

Test Class
it('::test SL  page', function() {
        pageObject.goToSpage();
        var currentURL=browser.getCurrentURL();
        expect(currentURL).toContain("SLink");
        *//ERROR HERE value in this variable "currentURL" is most of the 
        time Stale*
});

it('::test SL2  page', function() {
        pageObject.goToLpage();
        var currentURL=browser.getCurrentURL();
        expect(currentURL).toContain("Link");
        console.log("this line is always executed first"));
        //ERROR here , this print line is always executed first
});

Answer №1

Understanding Protractor documentation can be a bit confusing, particularly when it comes to synchronization. It appears that Protractor only waits for page synchronization when using the get or refresh commands. If you are using the click command to navigate to a new page, Protractor will not wait for synchronization before moving on. You can find more information about this behavior from a Protractor developer here.

In order to handle this in your test, you can implement a solution either directly in your test script or within a page object. One approach is to add the following code snippet after the click action:

browser.wait(function () {
    return browser.driver.getCurrentUrl().then(function (url) {
        return /SLink/.test(url);
    });
}, 10000);

This code will continuously check the current URL for the presence of the "Slink" string every 500 milliseconds for up to 10 seconds. Once the string is found, the next command will be executed.

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

Exploring the internet with the advanced capabilities of Angular JS

Encountering an issue with Internet Explorer and angular js. The html code displays correctly in Chrome and Firefox, but content within the ng-view tags does not appear in IE. <html xmlns:ng="http://angularjs.org"> <html lang="en" ng-app="poc"&g ...

Can you explain the meaning of <!-- in javascript?

Have you ever noticed the <!-- and --> characters being used around JavaScript code like this: <script type="text/javascript"> <!-- function validateForm() { if(document.pressed == 'Submit') { ...

A Promise-based value returned by a Typescript decorator with universal methods

I am currently working on creating a method decorator that can be applied to both prototype and instance methods. Referenced from: Typescript decorators not working with arrow functions In the code provided below, the instanceMethod() is returning a Prom ...

What is the process for verifying a Bootstrap form?

I have created a form using Bootstrap (Form component in ReactJS), but when I attempt to click on the submit button without entering any input, the form is still submitted. How can I implement form validation so that it only submits when all input fields a ...

The angular controller function is failing to set $scope.value

I've been facing an issue with setting an Angular variable value in a controller function that is created by a directive. For some reason, it doesn't seem to work when I try to assign the value within the controller function, even though it displ ...

Is there a way for me to programmatically modify a .env file using an npm script?

Currently, I'm managing a project with a .env file that contains confidential information. One of the key elements in this file is 'STATUS'. Just to clarify, this pertains to a Discord bot, The value assigned to the 'STATUS' var ...

PHP and MySQL combination for efficient removal of multiple dropdown choices

I'm struggling to figure this out. Essentially, it's a form with multiple dropdown menus where users can select one or more items to filter MySQL data results. I want to dynamically update the other dropdown menus as the user makes selections. Fo ...

Creating a dynamic image binding feature in Angular 8

I am working with an object array that requires me to dynamically add an image icon based on the type of credit card. Typescript file icon: any; savedCreditCard = [ { cardExpiryDateFormat: "05/xx", cardNumberLast: "00xx", cardId: "x ...

The process of embedding variables within a JSON Array function in JavaScript

As a newcomer to JavaScript, I am facing an issue while trying to create a simple program. I am attempting to store the variables 'name', 'document', and 'code' inside the JSON array called 'records'. var records = ...

Unable to reach the form within the confines of the AngularJS controller

I am attempting to manually reset a form from within an AngularJS controller, but I am unable to access it using either $scope or controllerAs. When I try to log $scope.SupportForm, it returns as undefined. HTML <form name="supportForm" id=&q ...

Responsive Bar Chart using jQuery Mobile and ChartJS that appears on the screen only after resizing

I have been experimenting with adding a responsive bar chart using Chart.js in one of my JQM projects. Here is what I have accomplished so far: http://jsfiddle.net/mauriciorcruz/1pajh3zb/3/ The Chart needs to be displayed on Page Two and it should be res ...

Ways to display URL parameters on an HTML page without using PHP

I'm currently working on a website using HTML (without PHP) and I'm facing an issue with displaying URL parameters on an appointment confirmation page. The appointment details are being successfully passed through the URL parameters, but I'm ...

What could be the reason behind Typescript's unexpected behavior when handling the severity prop in Material UI Alerts?

Trying to integrate Typescript into my react project and encountering a particular error: Type 'string' is not assignable to type 'Color | undefined'. The issue arises when I have the following setup... const foo = {stuff:"succes ...

What steps can I take to avoid unnecessary re-rendering of a variable that is not utilized in the HTML of my vue.js component?

I am currently in the process of replicating a real-life example of my code. In the actual code, this line represents a component that will continuously fetch an endpoint every few seconds, retrieving a random array of length "n", encapsulated wi ...

A step-by-step guide on simulating a click event on an element in React with the help of jest and react-testing

My component displays the following {list.options && list.options.length > 0 ? ( <div data-testId="MyAlertText" onClick={onAddText}> Add Text </div> ) : null} When testing, I am executing the following it('Ensure Add Text lin ...

Each time the page is refreshed, the most recent form data submitted is continually appended to an array

I have implemented a post request to add input data from a form. The entered data is stored in an array variable burg and then displayed on my index.handlebars view. Everything works as intended, but when the page is refreshed without any input in the form ...

Determining when all $http requests have completed in AngularJS

After running multiple $http calls, I need to trigger an event only when all of them have been processed. Additionally, I must be informed if any call has failed along the way. Despite attempting solutions found on stackoverflow, such as using an intercept ...

How can you fetch data from a PHP file using AJAX before performing a header redirect?

I am currently in the process of adding more dynamism to my website. I have developed a forum from scratch and now I am integrating JavaScript into it. All the PHP backend work is complete. My next goal is to enable user login without having to refresh the ...

Invoking a Node.js function using a URL reference

Is there a way to call a function located in a remote URL? I have the page URL and the function name. The server-side application is running on NodeJs Express, and the function structure is as follows: function executer(param1, param2){ //logic re ...

Using maxCDN to deliver static files within a Node application

Our current project is built using keystone and nunjucks, with all paths to static files following the format /stc/img/someimage.jpg. I am looking for a way to serve these files through middleware in our node server from maxCDN. Is there a solution that ...