{{announcement.body}}
{{announcement.title}}

Protractor Tutorial: Handling Timeouts With Selenium

DZone 's Guide to

Protractor Tutorial: Handling Timeouts With Selenium

When we run our test scripts without any instruction to wait, it’ll end up throwing an error; I’ll show you how to handle timeouts in this Protractor tutorial.

· Performance Zone ·
Free Resource

A lot of times while performing Selenium test automation, you’ll come across certain scenarios when your test fails because the webpage or the web element takes some time to load completely. In such scenarios, the best approach is to wait for the page or the web elements to load completely to avoid any errors due to timeout. These errors can be easily resolved if you know how to handle timeouts in Protractor with Selenium, as they help to set an interval of time before the next action is carried out. 

To make it even simpler let’s say you visit Amazon’s website, you find a special deals button, you click on it and it brings out a popup with the offer, which further takes you to the deals page. These different elements like the button and pop-up take some time to load and become interactive. But when we run our test scripts without any instruction to wait, it’ll end up throwing an error. To deal with this, we need to handle timeouts in Protractor with Selenium so that we give ample amount of time for the particular element to load.

So, to help you tackle this problem, I’ll show you how to handle timeouts in this Protractor tutorial. If you’re new to Protractor you can visit this Protractor tutorial on running your first test script for Protractor testing.

Timeout While Waiting For The Page To Load

While performing Selenium test automation to navigate a page on the browser, you’ll instruct the Selenium WebDriver to load the web page using the browser.get() command. Under the hood, the Protractor framework waits for the page to load completely. 

So let’s take a test case to handle timeouts in Selenium Protractor, where we set the timeout as 5000 ms or 5 secs, the browser will wait for the page to load until 5 sec and returns an error if the page takes more time to load.

For this, you’ll have to add getPageTimeout (timeout in milliseconds) to your protractor configuration file, to reflect the change in timeout globally. But in case you want to provide the timeout for individual test cases, you’ll have to pass an additional parameter when calling the browser.get()  i.e. browser.get ( address, the timeout in milliseconds ).

test_config.js

JavaScript
 




x
18


1
 
2
   specs: ['test_timeout.js'],
3
// overriding default value of getPageTimeout parameter //
4
      getPageTimeout: 10000,
5
      jasmineNodeOpts: {
6
// overriding default value of defaultTimeoutInterval parameter //
7
      defaultTimeoutInterval: 10000
8
   },
9
   onPrepare: function () {
10
      browser.manage().window().maximize();
11
      browser.manage().timeouts().implicitlyWait(3000);
12
   }
13
};
14
 
          
15
// launches the URL in the browser //
16
browser.get("http://the-internet.herokuapp.com");
17
 
18
 
          



Alternatively specifying the value as an argument to handle timeouts in Protractor with Selenium:

JavaScript
 




xxxxxxxxxx
1


1
// launches the URL in the browser and specifying the timeout as a parameter //
2
browser.get(http://the-internet.herokuapp.com,10000);



Timeout During Activity After Loading the Page

While performing any browser action on a page while performing Selenium test automation for Protractor testing, the javascript framework waits before proceeding with any action until there are no remaining asynchronous tasks in the application. It indicates that all the timeout along with the HTTP requests has been completed.

So let’s take a use case to handle timeouts in Protractor with Selenium where we set the default timeout as 6000 ms or 6 secs, the browser will wait after the page load before proceeding with any activity until 6 sec and then error out stating that it timed out waiting for asynchronous tasks to finish after 6000 ms.

For this, you’ll have to add allScriptsTimeout (timeout in ms) to the Protractor configuration file and this will reflect the change in timeout globally. 

test_config.js

JavaScript
 




xxxxxxxxxx
1
16


1
  specs: ['test_timeout.js'],
2
 
3
// overriding default value of getPageTimeout parameter //
4
      getPageTimeout: 10000,
5
// overriding default value of allScriptsTimeout parameter for Protractor testing//      
6
allScriptsTimeout: 10000,
7
 
8
      jasmineNodeOpts: {
9
// overriding default value of defaultTimeoutInterval parameter //
10
      defaultTimeoutInterval: 10000
11
   },
12
   onPrepare: function () {
13
      browser.manage().window().maximize();
14
      browser.manage().timeouts().implicitlyWait(3000);
15
   }
16
 
          



You can also fix this by making a change in the web applications for Protractor testing. Protractor waits indefinitely and then time out if the AngularJS application continuously checks $timeout or $http. You can use the $interval for any continuous polling as introduced in Angular 1.2. For Angular applications, Protractor must wait until the Angular Zone is stabilized. 

This means that long-running asynchronous operations would prevent your test from continuing. Hence, you’ll need to execute such tasks outside the Angular zone to have a workaround for this fix in this Protractor tutorial. For example:

JavaScript
 




xxxxxxxxxx
1


1
this.ngZone.runOutsideAngular(() => {
2
  setTimeout(() => {
3
    // Any changes that are made inside this will not be reflected in the view of our application for Protractor testing //
4
    this.ngZone.run(() => {
5
      // if we run inside this block then it will detect the changes. //
6
    });
7
  }, REALLY_LONG_DELAY);
8
});
9
 
          



Timeout When Waiting For The Variable To Be Initialized

When launching any URL in the browser for Protractor testing, the protractor waits for the angular variable to be present while loading a new page.

Let's take a use case to handle timeouts in Protractor with Selenium, where you set the default timeout as 8000 ms or 8 secs, the browser will wait for the angular variable on the page load before proceeding with any activity until 8 sec and return an error stating that angular could not be found on the page, retries looking for the angular exceeded.

For this, you’ll have to add getPageTimeout (timeout in millis) to your protractor configuration file to reflect the change in timeout globally. But in case if you want to provide the timeout individually during each loading of the web page in the browser, you’ll need to pass an additional parameter when calling the browser.get()  i.e. browser.get ( address, the timeout in milliseconds ).

test_config.js

JavaScript
 




xxxxxxxxxx
1
16


1
 specs: ['test_timeout.js'],
2
// overriding default value of getPageTimeout parameter to handle timeouts in Protractor with Selenium//
3
      getPageTimeout: 10000,
4
      jasmineNodeOpts: {
5
// overriding default value of defaultTimeoutInterval parameter //
6
      defaultTimeoutInterval: 10000
7
   },
8
   onPrepare: function () {
9
      browser.manage().window().maximize();
10
      browser.manage().timeouts().implicitlyWait(3000);
11
   }
12
};
13
 
          
14
// launches the URL in the browser //
15
browser.get("http://the-internet.herokuapp.com");
16
 
          



Alternatively specifying the value as an argument to handle timeouts in Protractor with Selenium

JavaScript
 




xxxxxxxxxx
1


1
// launches the URL in the browser and specifying the timeout as a parameter //
2
browser.get(http://the-internet.herokuapp.com,10000);



Test Specification Timeout in Protractor

The test specification i.e. the ‘it block’ of the Protractor testing case that defines the test case to be executed. In case the test case takes a long time to execute, for any reason like the processing of the test case, then ‘it’ block will fail and result in an error.

If we consider an example to handle timeouts in Protractor with Selenium, where the default timeout is set as 15000 ms or 15 secs, the browser will wait for the spec to complete execution until 15 sec and then fails the test results.

You need to add jasmineNodeOpts (timeout in millis) to the protractor configuration file to reflect the change in timeout globally. But in case we would like to provide the timeout individually for each test specification, we can achieve this by passing the third parameter in the ‘it’ block i.e. it(description, testFunc, a timeout in milliseconds).

test_config.js

JavaScript
 




xxxxxxxxxx
1
18


1
  specs: ['test_timeout.js'],
2
 
3
// overriding default value of getPageTimeout parameter to handle timeouts in Protractor Selenium //
4
      getPageTimeout: 10000,
5
// overriding default value of allScriptsTimeout parameter //      
6
allScriptsTimeout: 10000,
7
 
8
      jasmineNodeOpts: {
9
// overriding default value of defaultTimeoutInterval parameter //
10
      defaultTimeoutInterval: 30000
11
   },
12
   onPrepare: function () {
13
      browser.manage().window().maximize();
14
      browser.manage().timeouts().implicitlyWait(3000);
15
   }
16
 
          
17
 
          
18
 
          



Alternatively, bypassing as an argument.

JavaScript
 




xxxxxxxxxx
1


1
// describing the test for the timeout example //
2
   describe(' Timeout Demonstration in Protractor ', function() {
3
 // tests to handle timeouts in Protractor Selenium//
4
    it('Tests to handle timeouts in protractor', function() {
5
    // launch the url in the browser //   
6
       browser.get("http://the-internet.herokuapp.com ");   
7
   }, 30000);
8
});
9
 
          



Asynchronous Script Timeout in Protractor

The asynchronous script timeout is used to indicate the script to wait until the specified timeout limit so that it can complete its execution before the error is thrown to handle timeouts in Protractor Selenium. 

So let us take a use case to handle timeouts in Protractor with Selenium where we set the default timeout as 7000 ms or 7 secs, the browser will wait for any asynchronous task to complete its execution to handle timeouts in Protractor Selenium, before proceeding with its throwing an error until 7 sec and then results into a ScriptTimeoutError out stating that it timed out waiting for asynchronous tasks.

To modify this behavior to handle timeouts in Protractor Selenium, you need to add allScriptsTimeout (timeout in millis) to the protractor configuration file and this will reflect the change in timeout globally.

test_config.js

JavaScript
 




xxxxxxxxxx
1
17


1
specs: ['test_timeout.js'],
2
 
3
// overriding default value of getPageTimeout parameter for Protractor testing //
4
      getPageTimeout: 10000,
5
// overriding default value of allScriptsTimeout parameter //      
6
allScriptsTimeout: 10000,
7
 
8
      jasmineNodeOpts: {
9
// overriding default value of defaultTimeoutInterval parameter //
10
      defaultTimeoutInterval: 30000
11
   },
12
   onPrepare: function () {
13
      browser.manage().window().maximize();
14
      browser.manage().timeouts().implicitlyWait(3000);
15
   }
16
 
          
17
 
          



Ways to Toggle the Waiting Feature In Protractor

Whenever you want navigation or open a page in the browser that does not use Angular, we can disable this feature of waiting for timeout bypassing the argument as false when calling the function i.e.  browser.waitForAngularEnabled(false).

JavaScript
 




xxxxxxxxxx
1


1
browser.waitForAngularEnabled(false);
2
browser.get('/my_non_angular_page.html');
3
element(by.id('username')).sendKeys('myusername');
4
element(by.id('password')).sendKeys('mypassword');
5
element(by.id('clickButton')).click();
6
browser.waitForAngularEnabled(true);
7
browser.get('/my_page-containing-angular.html');
8
 
          



But we might get the Asynchronous Script TimeOut Exception from the WaitForAngular method. In such a case the first important thing would be to check on the timeout of our webdriver for scripts that have been set to something around 5 seconds for heavy and slowly loading websites.

Below is the complete code that demonstrates the behavior of handling timeouts in protractor.

test_config.js

JavaScript
 




xxxxxxxxxx
1
31


1
// setting required config parameters //
2
exports.config = {
3
   directConnect: true,
4
 
5
   // Desired Capabilities that are passed as an argument to the web driver instance.
6
   capabilities: {
7
      'browserName': 'chrome'  // name of the browser used to test //
8
   },
9
 
10
   // Flavor of the framework to be used for our test case //
11
     framework: 'jasmine',
12
 
13
   // The patterns which are relative to the current working directory when 
14
 
15
protractor methods are invoked //
16
 
17
   specs: ['test_timeout.js'],
18
// overriding default value of getPageTimeout parameter //
19
      getPageTimeout: 10000,
20
// overriding default value of allScriptsTimeout parameter //
21
      allScriptsTimeout: 10000,
22
      jasmineNodeOpts: {
23
// overriding default value of defaultTimeoutInterval parameter //
24
      defaultTimeoutInterval: 30000
25
   },
26
   onPrepare: function () {
27
      browser.manage().window().maximize();
28
      browser.manage().timeouts().implicitlyWait(5000);
29
   }
30
};
31
 
          



test_timeout.js

JavaScript
 




xxxxxxxxxx
1
30


1
// import all the required modules from selenium web driver and protractor
2
 
3
import 'selenium-webdriver';
4
 
5
import { browser, element, by, ExpectedConditions, protractor} from 'protractor'
6
 
7
 
8
   // describing the test for the timeout demonstration //
9
 describe('Timeout Demonstration in Protractor', function() {
10
    
11
browser.ignoreSynchronization = true; // disable synchronization for non  angular websites //
12
 
13
    // tests to handle timeouts in protractor //
14
    it('Tests to handle timeouts in protractor', function() {
15
 
16
    // launch the url in the browser //   
17
       browser.get(http://the-internet.herokuapp.com , 10000);
18
      
19
 browser.manage().timeouts().implicitlyWait(5000);
20
     
21
      // locate the element //                        
22
     element(by.xpath(" // label/ span ")).getAttribute("innerTextValue").then(function(textValue){
23
 
24
       // the value saved is assigned to the value of the text box
25
      element(by.xpath("//input[@type='text']")).sendKeys(textValue);
26
        })
27
    },30000);
28
});
29
 
30
 
          



Handle Timeouts in Protractor Selenium On Cloud Selenium Grid 

We can run the same Selenium test automation script to handle timeouts in Protractor Selenium on a cloud Selenium grid that provides the capability to run the tests across various real-time browsers and devices. To run Selenium test automation scripts for this Protractor tutorial, we just require configuration changes i.e. for building a driver to connect with the LambdaTest hub. Below is our revised script with the appropriate modifications for this Protractor tutorial to handle timeouts in Protractor Selenium. 

JavaScript
 




xxxxxxxxxx
1
137


1
// test_config.js //
2
// The test_config.js file serves as a configuration file for out Selenium test Automation case for this Protractor tutorial//
3
 
4
LT_USERNAME = process.env.LT_USERNAME || "irohitgoyal"; // LambdaTest User name
5
LT_ACCESS_KEY = process.env.LT_ACCESS_KEY || "r9JhziRaOvd5T4KCJ9ac4fPXEVYlOTealBrADuhdkhbiqVGdBg"; // LambdaTest Access key
6
 
7
exports.capabilities = {
8
  'build': ' Automation Selenium Webdriver Test Script ', // Build Name to be display in the test logs
9
  'name': ' Protractor Selenium Timeout Test on Chrome',  // The name of the test to distinguish amongst test cases //
10
  'platform':'Windows 10', //  Name of the Operating System
11
  'browserName': 'chrome', // Name of the browser
12
  'version': '79.0', // browser version to be used
13
  'console':false, // flag to check whether to capture console logs.
14
  'tunnel': false // flag to check if it is required to run the localhost through the tunnel
15
  'visual': false,  // flag to check whether to take step by step screenshot
16
  'network':false,  // flag to check whether to capture network logs
17
  };
18
 
19
// setting required config parameters //
20
exports.config = {
21
   directConnect: true,
22
 
23
   // Desired Capabilities that are passed as an argument to the web driver instance for Selenium test automation.
24
   capabilities: {
25
      'browserName': 'chrome'  // name of the browser used to test //
26
   },
27
 
28
   // Flavour of the framework to be used for our test case //
29
   framework: 'jasmine',
30
 
31
   // The patterns which are relative to the current working directory when 
32
 
33
protractor methods are invoked //
34
 
35
   specs: ['test_timeout.js'],
36
// overriding default value of getPageTimeout parameter //
37
      getPageTimeout: 10000,
38
// overriding default value of allScriptsTimeout parameter //
39
      allScriptsTimeout: 10000,
40
      jasmineNodeOpts: {
41
// overriding default value of defaultTimeoutInterval parameter //
42
      defaultTimeoutInterval: 30000
43
   },
44
   onPrepare: function () {
45
      browser.manage().window().maximize();
46
      browser.manage().timeouts().implicitlyWait(5000);
47
   }
48
};
49
 
          
50
 
          
51
// test_script.js //
52
 
53
// import all the required modules from selenium web driver and protractor
54
 
55
import { browser, element, by, ExpectedConditions, protractor} from 'protractor'
56
import 'selenium-webdriver';
57
 
58
var script = require (‘protractor’) ;
59
 
60
var webdriver = require (‘selenium-webdriver’) ;
61
 
62
// Build the web driver that we will be using in LambdaTest for this protractor tutorial
63
var buildDriver = function(caps) {
64
  return new webdriver.Builder()
65
    .usingServer(
66
      "http://" +
67
      LT_USERNAME +
68
      ":" +
69
      LT_ACCESS_KEY +
70
      "@hub.lambdatest.com/wd/hub"
71
    )
72
    .withCapabilities(caps)
73
    .build();
74
};
75
 
76
 
77
// describing the test for the timeout demonstration //
78
describe(' Timeout Demonstration in Protractor ', function() {
79
// disable synchronization for non  angular websites //
80
    browser.ignoreSynchronization = true;
81
 
82
// adding the before an event that builds the driver and triggers before the test execution
83
  beforeEach(function(done) {
84
    caps.name = this.currentTest.title;
85
    driver = buildDriver(caps);
86
    done();
87
  });
88
 
89
    // tests to handle timeout in Protractor Selenium//
90
    it(' Tests to handle timeout in protractor  ', function() {
91
 
92
 
93
      
94
 browser.manage().timeouts().implicitlyWait(5000);
95
     
96
      // locate the element for Protractor testing //                        
97
     element(by.xpath(" // label/ span ")).getAttribute("innerTextValue").then(function(textValue){
98
 
99
       // the value saved is assigned to the value of the text box
100
      element(by.xpath("//input[@type='text']")).sendKeys(textValue);
101
        })
102
    },30000);
103
});
104
 
105
 
106
 
107
 
108
 
109
        browser.manage().timeouts().implicitlyWait(5000)
110
       // launch the url in the browser //   
111
       browser.get(http://the-internet.herokuapp.com , 10000);                 
112
 
113
       // locate the element //                        
114
       
115
// Store the value in a web element
116
        WebElement ele1 = element(by.id("ele1")).getWebElement();
117
        // navigate to the next desired element i.e. ele1
118
        browser.switchTo().frame(ele1);
119
        // locate the new element i.e. element 3 //
120
        WebElement ele3 =         element(by.xpath("[@id='ele3']")).getWebElement();
121
        // using the switchTo method to navigate to ele 3
122
        browser.switchTo().frame(ele3);
123
        // search the element for the checkbox element by xpath locator
124
        WebElement checkbox  = element(by.xpath("//input[@type='checkbox']"));
125
        // if checkbox is not selected then click the checkbox
126
        checkbox.isSelected().then(function(checked){
127
            // if checkbox is not selected then click the checkbox
128
            if(! checked){
129
                checkbox.click();
130
            }
131
        })
132
            }
133
        });
134
    },30000);
135
});
136
 
137
 
          



As we saw in our example for this Protractor tutorial, that just by appending a few lines of code, we can connect to the LambdaTest Platform and run our Selenium test automation script on the Cloud Selenium grid. To have this setup, we are required to generate the desired capability matrix.

You can visit LambdaTest Selenium desired capabilities generator to generate the required configuration through which we can specify the environment in which we would like to perform our tests. Also, we just need to pass our LambdaTest username and access key in the configuration file that will uniquely identify us on the LambdaTest platform.

Below is the output on running the Selenium test automation script on LambdaTest for this Protractor tutorial:

lambdatest

Wrapping It Up!

This brings us to the conclusion of this Protractor tutorial on how to handle timeout in Protractor Selenium. Throughout this article, I explored how to handle timeout and explored different approaches for it. After implementing this in our test scripts you’ll realize that it makes Selenium test automation scripts more effective. This helps to perform automated browser testing of websites that have multiple asynchronous tasks and might take some time to render on the browser windows. If you want to learn how to handle alerts and popups in Protractor, you can refer to the article linked.

Moreover, adding a timeout to our web page allows components on our web page to have enough time to load. This makes Protractor one of the best frameworks to test timeout for Selenium test automation. Also, since we know that protractor is based on selenium and used primarily for automated browser testing, it inherits many of its properties. Finally, there are many other functionalities of the framework available which I’ll discuss in the future Protractor tutorial.

I’d love to hear your opinion on this article in the comment section down below. Also, feel free to share this article with your friends on LinkedIn, Twitter, or any other social media platform. That’s all for now. 

Happy Testing!

Topics:
automation testing, javascript developers, javascript framework, performance, protractor, selenium automated testing, selenium automation, selenium webdriver, tutorial

Published at DZone with permission of Praveen Mishra , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}