Require assistance with try-catch statements

I am troubleshooting an issue with a try-catch block in my Protractor test. Take a look at the code snippet below:

try {
    element(by.id('usernameas')).sendKeys(data);
}
catch(err) {
    console.log('error occurred');
} 

To test the functionality, I intentionally provided an incorrect locator to see if it triggers the catch block. However, instead of entering the catch block as expected, I receive a NoSuchElementError on the command prompt and the test execution halts.

Your suggestions are appreciated.

Answer №1

When you call element(locator).sendKeys, a promise is returned that can either be resolved or rejected. This promise plays a role in the test's control flow.

The actual call to element(locator) does not cause an error; it's the rejection of the promise that signifies an issue. If you are unable to locate the desired element, your entire test should fail because the scenario cannot proceed.

To access the error message, utilize the promise callbacks as shown below.

It's crucial to note: handling the promise failure on your own will prevent the test from failing, so it's advisable to rethrow the error.

try {
    element(by.id('usernameas')).sendKeys(data).then(function() {
        console.log('Keys sent successfully');
    }, function(err) {
        console.error('Error sending keys ' + err);
        throw err;
    });
}
catch(err) {
    console.log('An error occurred');
}

The console output is displayed as follows:

Error sending keys NoSuchElementError: no such element
  (Session info: chrome=31.0.1650.63)
  (Driver info: chromedriver=2.8.241075,platform=Windows NT 6.1 S .....

Answer №2

Encountering a similar issue recently made me realize that the try/catch block is not necessary in Protractor. Instead, you can implement error handling like this:

try {  
  loadWebApp();
  login();
  openUserPreferences();
  changePassword();
 } catch (err) {
  console.error(
      "An error was thrown! " + err);
 }

 loadWebApp().
    then(login).
    then(openUserPreferences).
    then(changePassword).
    then(null, function(err) {  
      console.error(
          "An error was thrown! " + err);
    });

You can find more information on this approach at: https://code.google.com/p/selenium/wiki/WebDriverJs#Promises
under Value Propagation and Chaining

To reiterate, there's no need for a traditional try/catch block.

In essence, this method works because

a promise can either be RESOLVED or REJECTED and in case of a rejected or failed promise, this line [ then(null, function(err) { ... } ] will act as the CATCH block.


It's important to note that the then(null, function(err))( does not require a callback but only an errBack; indicating that we are only concerned with failures and not with successful resolution, hence the NULL for callback and the function(error) for the errBack.
No need to wrap this in a try/catch and throw the error as suggested previously in the accepted answer (@Eitan Peer).

Hopefully, this explanation proves beneficial to those grappling with Protractor challenges, much like I did.

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

"Utilizing AngularJS to connect function with the start, end, and error events of an

Is there a way to automatically trigger a function every time Angular makes an $http request? I want to display a loading spinner whenever an Ajax Request is being made by the app. In the past, in jQuery, I have achieved this by using the following code: ...

Issue with directive not activating when attribute is changed

I am facing an issue with my website where users can make selections from two dropdowns, and based on those values, attributes are sent to directives for a corresponding function to be called. The problem I'm encountering is that the directives are n ...

Inquiry on integrating Spotify with Axios for my debut solo project (beginner inquiry)

I have a question regarding my first solo project in React. I started learning code in September and I'm facing an issue while making a POST request to the Spotify API to retrieve an access token: Despite following the recommended 'Content-Type& ...

String ES6 syntax immediately after function

return pool.query`select * from mytable where id = ${value}` How can the code snippet above be rewritten in full JavaScript? I attempted to use: return pool.query(`select * from mytable where id = $(value)`) but it seems like there is a difference. Th ...

AngularJS is throwing a $injector:modulerr error and I've exhausted all possible solutions

I recently started learning Angular and I've been following the tutorial on the official AngularJS website. Here's what I've tried so far: Installed angular-route and included the script below angular.min.js Utilized ngRoute in my mod ...

Loop through a JSON object to dynamically update the value of a specific key

I have a JSON object with keys and values, where some of the values are empty strings. I want to replace those empty values with the corresponding key name. However, when trying to get the value of a key within the loop, it returns undefined. JSON: "Forg ...

Separate modules in the Webpack.mix.js file don't produce any output files in the public folder

I've recently been tackling a Laravel project with an extensive webpack.mix.js file residing in the root directory, boasting nearly 5000 lines of code. In an effort to enhance organization and maintainability, I've opted to break it down into ind ...

Using Cucumber for testing javascript-loaded content can be incredibly powerful and effective in ensuring the functionality

As I develop my Rails application, I've decided to incorporate a combination of Test Driven Development and Behavioral Driven Development into my process. The challenge arises as my app utilizes the MochaUI web application user interface framework, w ...

Capturing HTML form values and storing them in my JavaScript data object

I have a JS object with preset data as shown below in the variable var json. I am trying to create a simple HTML web form where I want the user inputs to be added as a new data set within my initial JS object. Here is the initial JS object data. The submi ...

Is there a way to showcase a row of images when a button is clicked?

I am looking to create a functionality where pressing one of the buttons shown in the image below will toggle visibility of specific sections containing 3 images each. For example, clicking on "Tapas" will only display tapas images and hide main course ima ...

`How can I effectively integrate react-i18next with the Semantic UI label element?`

Currently, I am working with Semantic UI along with the integration of [react-i18next][2]. My goal is to enable translation for label strings, but these labels include HTML tags, such as span. Unfortunately, the system only allows hardcoded or variable s ...

Bypass ajax request with the use of a returned promise

I've come across a scenario where I have a function within a class that is designed to return a promise for deleting an item. Here's what the function looks like: function Delete(){ // if(this.id == ""){ // return ?; // } ...

Is there a way to detect when a user is interacting with a form item using Vue and Buefy?

I'm interested in activating an event when a user focuses on a form element created using Vue / Buefy. As a newcomer to this, I would appreciate any guidance on how to accomplish this triggering action. ...

Implementing Conditional Class Addition in React.js

Currently, I am utilizing Reactjs (Nextjs) to work on my project. The project consists of a "Home page" as well as several other pages such as about and services. To integrate these pages in Nextjs, I created "_document.js". However, I have encountered a ...

Verify if the user is already present in the MongoDB database and authenticated with Passport

I'm currently exploring the usage of passport and I am in the process of setting up a "register" page functionality. The registration process is working smoothly, along with the log-in form. Yet, I am looking to implement a validation to check if the ...

having trouble adjusting the width of the buefy modal

Currently, I am working with vuejs alongside bulma and buefy. Specifically, I am utilizing the buefy modal feature and attempting to customize the modal width by utilizing its 'width' property. Thus far, I have attempted specifying the width in t ...

Preventing the submission of a form using jQuery until all input, radio, select, and checkbox fields are filled out

I currently have a form that includes various field types, all of which must be filled out before submission. The submit button is disabled by default and I am looking to enable it once all fields are completed. I came across examples of this feature work ...

Struggling to get the AJAX code functioning correctly

Embarking on my journey with AJAX, I decided to test a simple example from the Microsoft 70515 book. Surprisingly, the code doesn't seem to be functioning as expected and I'm at a loss trying to figure out why - everything appears to be in order. ...

What is preventing React CLI from installing the template as TypeScript?

When I run npm init react-app new-app --template typescript, it only generates a Javascript template project instead of a Typescript one. How can I create a Typescript project using the CLI? Current Node JS version: 15.9.0 NPM version: 7.0.15 ...

navigating through a specific section of a data chart

I need the first column of a table to stay fixed while the rest of the columns scroll horizontally. Here's the code I have: <div id="outerDiv"> <div id="innerDIv"> <table> <tr><td>1</td><t ...