Dealing with Errors in Angular Protractor

As a newcomer to using Protractor for automating AngularJS applications, I am encountering difficulties in selecting an element from a list due to issues with error handling caused by promises.

In the given code snippet, when providing an invalid categoryName, instead of displaying the error message it proceeds to the verification part and fails.

I have tried implementing callback functions without success, as well as utilizing try-catch blocks with no luck either. Any guidance on understanding and resolving this issue would be greatly appreciated. Thank you.

this.elements = element.all(by.css('.xyz'));
this.selectCategory = function (categoryName) {
    this.elements.each(function (category) {
        category.getText().then(function (text) {
            if (text === categoryName) {
                log.info("Selecting Category");
                category.click();
            }
        }, function (err) {
            log.error('error finding category ' + err);
            throw err;
        });
    })
};

Answer №1

To filter elements and determine the number of matches, utilize the filter() method:

let filteredResults = this.elements.filter(function (element) {
    return element.getText().then(function (text) {
        return text === desiredText;
    });
});  
expect(filteredResults.count()).toEqual(1);
filteredResults.first().click();

Answer №2

To track Invalid scenarios, simply follow these steps:

this.selectCategory = function (categoryName) {

    var filteredCategories = this.categoryElements.filter(function (category) {
        return category.getText().then(function (text) {
            return text === categoryName;
        })
    })

    filteredCategories.count().then(logInvalidCase)

    expect(filteredCategories.count()).toEqual(1);
    filteredCategories.first().click();
}

function logInvalidCase(count) {

   if(count === 0) {
       log.info("Log: Invalid Scenario Detected");
   }
}

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

What Mistakes am I Making in Utilizing Typeahead.js Prefetch?

For the past week, I've been attempting to make typeahead.js (https://github.com/twitter/typeahead.js) work. I've managed to get the local version functioning as expected, but the prefetch feature refuses to cooperate. I have a results.json file ...

Secure access to an API using a certificate within a Vue.js application running on localhost

My vue.js app is built using vue-cli. The application is hosted at dev.example.com and the REST API can be found at dev.example.com/api/v1/. The backend has added an SSL certificate for security on the development environment. However, when I try to make a ...

A solution for Array.includes to handle NaN values

While browsing some Javascript blogs, I stumbled upon the Array prototype methods .indexOf and .includes. I noticed that if an array includes NaN as a value, indexOf may not be able to detect it, leaving us with the option of using .includes. However, cons ...

I possess a pair of arrays, and I aim to transfer certain elements from Array1 to Array2 while maintaining their references

Looking to implement two JavaScript arrays using AngularJS. My goal is to transfer elements from Ar1 to Ar2, and then have any changes made to the values in Ar2 automatically update the values in Ar1 as well. ...

Vue.js: Why isn't the view updating when the data changes?

<div id="app"> <h1> Latest News </h1> <div v-for="CurArticle in articles"> <div id="title"> <h2>{{CurArticle.title}}</h2> </div> <div id="content"> <p>{{CurArticle.content}}</p> </div> ...

When attempting to open a popup form by clicking a button, the code fails to function on IE6

Everything seems to be running smoothly on Firefox, however I am encountering issues with Internet Explorer 6. Here is a snippet of the problematic code: document.getElementById('layout').style.opacity = .7 document.getElementById('layout&a ...

"Converting a standard grammar with recursion and alternations into a regular expression: A step-by-step

A grammar is considered regular if it follows either a right-linear or left-linear pattern. According to this tutorial, this type of grammar possesses a unique property: Regular grammars have a special characteristic: through the substitution of every no ...

modifying the source of an Ajax POST request

Is it possible to modify the referrer in an HTTP Ajax call using jQuery or JavaScript? I'm looking to send a request from my page but have the referrer appear as though it came from another page. Any insights would be appreciated. ...

What steps should I take to troubleshoot the issue when utilizing full HTML link paths in my links?

I have come across the recommendation to use full link paths between pages on my website for various reasons. However, I am concerned about how to debug and work on my local testing environment when all of the links are using full paths. (Manually replaci ...

Is it possible to omit specific files from an NPM package during installation?

Is there a way to omit specific files from the list of NPM packages in my package.json? In my unique non-browser environment, every file within the node_modules directory automatically becomes part of the final production package. This means that there is ...

JQuery form serialize not triggering in Internet Explorer

I've encountered an issue with a form inside a jQuery dialog that is not submitting properly in Internet Explorer. The form functions correctly in Chrome and Firefox, sending data to my MVC controller without any issues. However, when using IE, it on ...

Error in AngularJS ngRepeat Syntax

While using AngularJS v1.3.15 I encountered a strange syntax error: http://errors.angularjs.org/1.3.15/ngRepeat/iexp?p0=item%20asNaNtems This is the code snippet from my template (templateUrl): <div class="context-menu" ng-if="showMenu"> &l ...

Is there a way for me to dynamically retrieve the input value produced by the Query?

Is there a way to retrieve the value of a dynamically created input field? $('#inputArea').append(" <input id = "arrivalTime1" type = 'number' placeholder='Arrival Time' style = 'display: none;'> " ...

When the button is clicked, display in the console the data retrieved from the API

Programming Section import react, { useEffect } from 'react'; import './styles.css'; export default function App() { useEffect(() => { fetch('https://jsonplaceholder.typicode.com/todos') .then((response) => ...

Transferring the $http.post request to a separate service function

Although I am new to AngularJS, I assure you that I am not stupid. I recently had a call in a controller that I wanted to move to a service in order to make it available to multiple controllers. $http.post("/admin/Leads/LoadLeads.ashx", dataObj) .succ ...

The issue with Three.Js Raycasting arises when attempting to change camera transformations within an Object3D parent element

In my latest project, I decided to create a "camera controller" that handles the movement and rotation of the camera by utilizing an Object3D as its parent. The Y-axis rotations are applied to the Object3D, while the X-axis rotation is directly applied to ...

Reacting to URL Changes but Failing to Load the Requested Page

Welcome to my App Component import React, { useEffect } from 'react'; import './App.css'; import Navbar from './components/layout/Navbar'; import Landing from './components/layout/Landing'; import { BrowserRouter as ...

Updating a behavior object array in Angular 5 by appending data to the end

After creating a service to share data across my entire application, I'm wondering if it's possible to append new data to an array within the userDataSource. Here is how the service looks: user.service userDataSource = BehaviorSubject<Array& ...

Combine arrays using ES5 syntax. Join arrays to form a single array

I need help merging chunks of arrays into a single array of objects using AngularJS. My initial input array looks like this: [ [ { "title": "asd", "description": "asd" }, { "title": "asz", "description": "sd" } ...

Executing a Visual Basic subroutine from a jQuery dialog box

Currently, I have a form that includes a jQuery dialog creation. Within this dialog, there is a button generated from an ASP server control that should trigger a function in the code behind when clicked. However, I am encountering an issue where the functi ...